WinForm对EXCEL的操作(三)
终于有时间可把下面的WinForm对EXCEL的操作方法与大家分享了。前面介绍了如何把获取SHEET名称和如何获取SHEET里面数据两种方法。其实这两种方法都是在为EXCEL数据导入数据库作准备,至数据怎么导入数据库将会在以后学习不断分享给大家。下面就介绍下如何把数据放SHEET中:
方法1:
View Code
1 publicvoidDataToExcel(DataTable dt)
2 {
3 try
4 {
5 if(dt == null) return;
6
7 Microsoft.Office.Interop.Excel.ApplicationClass myExcel = newMicrosoft.Office.Interop.Excel.ApplicationClass();
8 Microsoft.Office.Interop.Excel.Workbook xBk; //工作薄 9 Microsoft.Office.Interop.Excel.Worksheet xSt; //工作Sheet
10
11 xBk = myExcel.Workbooks.Add(true);
12 xSt = (Microsoft.Office.Interop.Excel.Worksheet)xBk.ActiveSheet;
13
14 myExcel.Visible = true;
15
16 for(inti = 1; i <= dt.Columns.Count; ++i)
17 {
18 xSt.Cells[1, i] = dt.Columns[i - 1].ColumnName;
19 }
20
21 for(inti = 2; i <= dt.Rows.Count + 1; ++i)
22 {
23 for(intj = 1; j <= dt.Columns.Count; ++j)
24 {
25 xSt.Cells[i, j] = dt.Rows[i - 2][j - 1].ToString();
26 }
27 }
28
29 for(inti = 1; i <= dt.Columns.Count; ++i)
30 {
31 Microsoft.Office.Interop.Excel.Range selectRange = xSt.get_Range(xSt.Cells[1, i], xSt.Cells[dt.Rows.Count + 1, i]);
32 selectRange.Columns.AutoFit();
33 }
34 }
35 catch
36 {
37
38 }
39 }
方法2:
View Code
1 publicvoiddataToExcel(DataTable dt)
2 {
3
4 SaveFileDialog dlg = newSaveFileDialog();
5 dlg.Filter = "Execl files (*.xls)|*.xls";
6 dlg.FilterIndex = 0;
7 dlg.RestoreDirectory = true;
8 dlg.Title = "保存为Excel文件";
9 dlg.FileName = DateTime.Now.Ticks.ToString().Trim();
10
11 if(dlg.ShowDialog() == DialogResult.OK)
12 {
13 Stream myStream = dlg.OpenFile();
14 StreamWriter sw = newStreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
15 stringcolumnTitle = "";
16 try
17 {
18 //写入列标题
19 for(inti = 0; i < dt.Columns.Count; i++)
20 {
21 if(i > 0)
22 {
23 columnTitle += "\t";
24 }
25
补充:Web开发 , ASP.Net ,