C#中DataGridView導(dǎo)出Excel的兩種方法
第一種是用數(shù)據(jù)流導(dǎo)出:
#region SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "Export Excel File"; saveFileDialog.ShowDialog(); if (saveFileDialog.FileName == "") return; Stream myStream; myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = ""; try { for (int i = 0; i < dataGridView1.ColumnCount; i++) { if (i > 0) { str += "\t"; } str += dataGridView1.Columns[i].HeaderText; } sw.WriteLine(str); for (int j = 0; j < dataGridView1.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < dataGridView1.Columns.Count; k++) { if (k > 0) { tempStr += "\t"; } tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); } #endregion
這種方法的優(yōu)點(diǎn)就是導(dǎo)出比較快,但是excel的表格里面設(shè)置標(biāo)題,字體樣式等都不能弄,因?yàn)槟闶怯脭?shù)據(jù)流直接導(dǎo)出為excel的,除非你能在數(shù)據(jù)流中設(shè)置這些樣式,這個(gè)我還沒(méi)這本事,哪位大哥會(huì)的教一下...嘿嘿
第二種方法是直接寫一個(gè)類,這個(gè)類直接操作EXCEL的:
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Text; using System.Diagnostics; using System.IO; using Microsoft.Office.Interop.Excel; namespace Excel { public class Export { /// <summary> /// DataGridView導(dǎo)出Excel /// </summary> /// <param name="strCaption">Excel文件中的標(biāo)題</param> /// <param name="myDGV">DataGridView 控件</param> /// <returns>0:成功;1:DataGridView中無(wú)記錄;2:Excel無(wú)法啟動(dòng);9999:異常錯(cuò)誤</returns> public int ExportExcel(string strCaption, DataGridView myDGV, SaveFileDialog saveFileDialog) { int result = 9999; //保存 saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; //saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "Export Excel File"; if ( saveFileDialog.ShowDialog()== DialogResult.OK) { if (saveFileDialog.FileName == "") { MessageBox.Show("請(qǐng)輸入保存文件名!"); saveFileDialog.ShowDialog(); } // 列索引,行索引,總列數(shù),總行數(shù) int ColIndex = 0; int RowIndex = 0; int ColCount = myDGV.ColumnCount; int RowCount = myDGV.RowCount; if (myDGV.RowCount == 0) { result = 1; } // 創(chuàng)建Excel對(duì)象 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); if (xlApp == null) { result = 2; } try { // 創(chuàng)建Excel工作薄 Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1]; // 設(shè)置標(biāo)題 Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //標(biāo)題所占的單元格數(shù)與DataGridView中的列數(shù)相同 range.MergeCells = true; xlApp.ActiveCell.FormulaR1C1 = strCaption; xlApp.ActiveCell.Font.Size = 20; xlApp.ActiveCell.Font.Bold = true; xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; // 創(chuàng)建緩存數(shù)據(jù) object[,] objData = new object[RowCount + 1, ColCount]; //獲取列標(biāo)題 foreach (DataGridViewColumn col in myDGV.Columns) { objData[RowIndex, ColIndex++] = col.HeaderText; } // 獲取數(shù)據(jù) for (RowIndex = 1; RowIndex < RowCount; RowIndex++) { for (ColIndex = 0; ColIndex < ColCount; ColIndex++) { if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string) || myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//這里就是驗(yàn)證DataGridView單元格中的類型,如果是string或是DataTime類型,則在放入緩存時(shí)在該內(nèi)容前加入" "; { objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value; } else { objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value; } } System.Windows.Forms.Application.DoEvents(); } // 寫入Excel range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]); range.Value2 = objData; xlBook.Saved = true; xlBook.SaveCopyAs(saveFileDialog.FileName); } catch (Exception err) { result = 9999; } finally { xlApp.Quit(); GC.Collect(); //強(qiáng)制回收 } //返回值 result = 0; } return result; } } }
這個(gè)優(yōu)點(diǎn)是能設(shè)置樣式什么的。缺點(diǎn)就是導(dǎo)出速度慢...
以上兩種方法都是參考了很多料的..寫在這里以便于相互學(xué)習(xí)..
補(bǔ)充一下:用第二種方法導(dǎo)出excel會(huì)有格式方面的變化,比如身份證號(hào)碼按科學(xué)計(jì)算法導(dǎo)出了,不是按原先的模型
改進(jìn)方法是在寫入excel時(shí)添加一個(gè)格式聲明:range.NumberFormatLocal = "@";
如:// 寫入Excel
range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount + 2, ColCount]); range.NumberFormatLocal = "@"; range.Value2 = objData;
到此這篇關(guān)于C#中DataGridView導(dǎo)出Excel的兩種方法的文章就介紹到這了,更多相關(guān)C# DataGridView導(dǎo)出Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C#如何將DataTable導(dǎo)出到Excel解決方案
- C#操作EXCEL DataTable轉(zhuǎn)換的實(shí)例代碼
- C#將Excel中的數(shù)據(jù)轉(zhuǎn)換成DataSet
- C#實(shí)現(xiàn)將DataTable內(nèi)容輸出到Excel表格的方法
- C#使用Datatable導(dǎo)出Excel
- C#把EXCEL數(shù)據(jù)轉(zhuǎn)換成DataTable
- C#把DataTable導(dǎo)出為Excel文件
- C#實(shí)現(xiàn)讀取Excel文件并將數(shù)據(jù)寫入數(shù)據(jù)庫(kù)和DataTable
- C#中ExcelDataReader的具體使用
相關(guān)文章
C# System.BadImageFormatException問(wèn)題及解決
這篇文章主要介紹了C# System.BadImageFormatException問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05C#使用DateTime.Now靜態(tài)屬性動(dòng)態(tài)獲得系統(tǒng)當(dāng)前日期和時(shí)間
本文主要介紹了C#使用DateTime.Now靜態(tài)屬性動(dòng)態(tài)獲得系統(tǒng)當(dāng)前日期和時(shí)間,DateTime結(jié)構(gòu)的Now靜態(tài)屬性只是得到一個(gè)系統(tǒng)時(shí)間對(duì)象,該時(shí)間對(duì)象不會(huì)隨著系統(tǒng)時(shí)間的變化而變化,如果要?jiǎng)討B(tài)顯示系統(tǒng)時(shí)間,可以使用計(jì)時(shí)器間隔地獲取系統(tǒng)時(shí)間對(duì)象并顯示,感興趣的可以了解一下2024-01-01C#?WinForm?RichTextBox文本動(dòng)態(tài)滾動(dòng)顯示文本方式
這篇文章主要介紹了C#?WinForm?RichTextBox文本動(dòng)態(tài)滾動(dòng)顯示文本方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03C# WPF上位機(jī)實(shí)現(xiàn)和下位機(jī)TCP通訊的方法
這篇文章主要介紹了C# WPF上位機(jī)實(shí)現(xiàn)和下位機(jī)TCP通訊的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03