DataTable数据存入指定路径的Excel文件

如题,将DataTable的数据存入指定路径的Excel文件中,具体方法如下:

  1         /// <summary>
  2         /// 将DataTable的数据存到指定路径的Excel文件中
  3         /// </summary>
  4         /// <param name="dt">DataTable</param>
  5         /// <param name="strFileName">文件名</param>
  6         public static void DataTable2Excel(DataTable dt, string strFileName)
  7         {
  8             // Need an Excel App to save document. If Excel is not installed on the user computer, there will be an error message.
  9             Excel.Application myExcelApp = new Excel.Application();
 10             if (myExcelApp == null)
 11             {
 12                 MessageBox.Show("ERROR: EXCEL couldn't be started!");
 13                 System.Windows.Forms.Application.Exit();
 14             }
 15 
 16             // Let the App create a workbook and a worksheet in the workbook
 17 
 18             Excel.Workbook myWorkbook = (Excel.Workbook)myExcelApp.Workbooks.Add(Type.Missing);
 19             Excel.Style styHeader; styHeader = myWorkbook.Styles.Add("STYLE_HEADER", Type.Missing);
 20             Excel.Style styText;
 21 
 22             // styText = myWorkbook.Styles["STYLE_TEXT"];
 23 
 24             styText = myWorkbook.Styles.Add("STYLE_TEXT", Type.Missing);
 25             while (myWorkbook.Sheets.Count > 1)
 26             {
 27                 ((Excel.Worksheet)myWorkbook.Worksheets[1]).Delete();
 28             }
 29             //for (int m = 1; m < 4; m++)
 30             //{
 31             Excel.Worksheet myWorksheet = (Excel.Worksheet)myWorkbook.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
 32             //A new workbook contains 3 sheets by default, we need to clear all these blank sheet after adding a new one                 
 33 
 34             ((Excel.Worksheet)myWorkbook.Worksheets[1]).Name = "sheet1";
 35 
 36             // iHeaderOffset = 0 means NOT include the column names in the Excel worksheet
 37             // iHeaderOffset = 1 means include the column names as the first line in the Excel worksheet
 38             int iHeaderOffset = 0;
 39 
 40             iHeaderOffset = 1;
 41 
 42             // Make the column names in DB the HEADER of the worksheet
 43             for (int j = 0; j < dt.Columns.Count; j++)
 44             {
 45                 myWorksheet.Cells[1, j + 1] = dt.Columns[j].ColumnName;
 46             }
 47 
 48 
 49             #region styHeader
 50 
 51             //try
 52             //{
 53             //    styHeader = myWorkbook.Styles["STYLE_HEADER"];
 54             //}
 55             //catch
 56             //{
 57             //    styHeader = myWorkbook.Styles.Add("STYLE_HEADER", Type.Missing);
 58             //}
 59 
 60             styHeader.Font.Name = "Arial";
 61             styHeader.Font.Bold = true;
 62             styHeader.Font.Size = 10;
 63             styHeader.Font.Color = ColorTranslator.ToOle(Color.White);
 64             styHeader.Interior.Color = ColorTranslator.ToOle(Color.DarkBlue);
 65             styHeader.Interior.Pattern = Excel.XlPattern.xlPatternSolid;
 66             Excel.Range rng = myWorksheet.Range[myWorksheet.Cells[1, 1], myWorksheet.Cells[1, dt.Columns.Count]];
 67             //rng.Columns.Cells.WrapText = true;
 68             //rng.Columns.WrapText = true;
 69             //rng.Cells.Width = 20;
 70             //rng.ColumnWidth = 12;
 71             rng.Style = "STYLE_HEADER";
 72 
 73             #endregion styHeader
 74 
 75 
 76             #region styText
 77 
 78 
 79             //styText.Font.Name = "Arial";
 80             styText.Font.Bold = false;
 81             styText.Font.Size = 10;
 82             styText.Font.Color = ColorTranslator.ToOle(Color.Black);
 83             styText.NumberFormat = "@";
 84             //styText.Interior.Color = ColorTranslator.ToOle(Color.White);
 85             //styText.Interior.Pattern = Excel.XlPattern.xlPatternSolid;
 86             #endregion styText
 87 
 88             for (int i = 0; i < dt.Rows.Count; i++)
 89             {
 90                 for (int j = 0; j < dt.Columns.Count; j++)
 91                 {
 92 
 93                     Excel.Range rng1 = (Excel.Range)myWorksheet.Cells[i + 1 + iHeaderOffset, j + 1];
 94                     rng1.Style = "STYLE_TEXT";
 95                     //rng1.Columns.WrapText = true;
 96                     // rng.Cells.Width = 20;
 97                     //rng1.ColumnWidth = 12;
 98                     myWorksheet.Cells[i + 1 + iHeaderOffset, j + 1] = dt.Rows[i][j].ToString().Trim();
 99                 }
100             }
101 
102             // Make the output looks good
103             myWorksheet.UsedRange.Columns.AutoFit();
104 
105             // Save the XLS file
106             myWorkbook.SaveAs(strFileName,         // Filename
107                                  Excel.XlFileFormat.xlXMLSpreadsheet,   // FileFormat
108                                  Type.Missing,                          // Password
109                                  Type.Missing,                          // WriteResPassword,
110                                  false,                                 // ReadOnlyRecommended,
111                                  false,                                 // CreateBackup,
112                                  Excel.XlSaveAsAccessMode.xlNoChange,   // AccessMode,
113                                  Type.Missing,                          // ConflictResolution,
114                                  Type.Missing,                          // AddToMru,
115                                  Type.Missing,                          // TextCodepage,
116                                  Type.Missing,                          // TextVisualLayout,
117                                  Type.Missing                           // Object Local
118                             );
119 
120 
121             //Close the XLS file.
122             myWorkbook.Close(true, Type.Missing, Type.Missing);
123             myExcelApp.Quit();
124             System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorksheet);
125             System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorkbook);
126             System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcelApp);
127             myWorksheet = null;
128             myWorkbook = null;
129             myExcelApp = null;
130             GC.Collect();
131 
132 
133 
134         }


 

posted @ 2012-05-03 16:24  IT女汉纸  阅读(394)  评论(0编辑  收藏  举报