1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. using Excel = Microsoft.Office.Interop.Excel; 
  6. using System.Collections; 
  7. using System.Windows.Forms; 
  8. using System.Data; 
  9. namespace TableToExcel 
  10.     class Table_ToExcel 
  11.     { 
  12.         public Excel.Application m_xlApp = null
  13.         #region 外部接口 
  14.         /// <summary>将一个DataTable的数据导出多个Excel文件(每一个Excel文件的数据行数由函数控制) 
  15.         /// 将一个DataTable的数据导出多个Excel文件(每一个Excel文件的数据行数由函数控制) 
  16.         /// </summary> 
  17.         /// <param name="tempDataTable">数据源</param> 
  18.         /// <param name="PathFileName">保存excel的路径</param> 
  19.         /// <param name="ExcelRows">每一个Excel文件的行数</param> 
  20.         /// <param name="ExcelVersion">导出Excel的版本(2003,2007)</param> 
  21.         public void u_DataTableToExcel1(DataTable tempDataTable, string PathFileName, long ExcelRows, string ExcelVersion) 
  22.         { 
  23.             if (tempDataTable == null
  24.             { 
  25.                 return
  26.             } 
  27.             long rowNum = tempDataTable.Rows.Count;//导出数据的行数    
  28.             int columnNum = tempDataTable.Columns.Count;//导出数据的列数    
  29.             string sFileName = ""
  30.             if (rowNum > ExcelRows) 
  31.             { 
  32.                 long excelRows = ExcelRows;//定义个excel文件显示的行数,最大的行数为65535,不能超过65535                      
  33.                 int scount = (int)(rowNum / excelRows);//生成excel文件的个数    
  34.                 if (scount * excelRows < rowNum)//当总行数不被excelRows整除时,经过四舍五入可能excel的个数不准    
  35.                 { 
  36.                     scount = scount + 1; 
  37.                 } 
  38.                 for (int sc = 1; sc <= scount; sc++) 
  39.                 { 
  40.                     int init = int.Parse(((sc - 1) * excelRows).ToString()); 
  41.                     sFileName = PathFileName + sc.ToString(); 
  42.                     long start = init; 
  43.                     long end = sc * excelRows - 1; 
  44.                     if (sc == scount) 
  45.                         end = rowNum-1; 
  46.                     u_OutExcel(tempDataTable, start, end, sFileName, ExcelVersion); 
  47.                 } 
  48.             } 
  49.             else 
  50.             { 
  51.                 u_OutExcel(tempDataTable, 0, rowNum-1, PathFileName, ExcelVersion); 
  52.             } 
  53.         } 
  54.         /// <summary>将一个DataTable的数据导出一个Excel文件:可能包含多个sheet文件,由sheet行数决定 (每一个sheet文件的行数由函数控制) 
  55.         /// 将一个DataTable的数据导出一个Excel文件:可能包含多个sheet文件,由sheet行数决定 (每一个sheet文件的行数由函数控制) 
  56.         /// </summary> 
  57.         /// <param name="tempDataTable">数据源</param> 
  58.         /// <param name="PathFileName">导出excel的路径</param> 
  59.         /// <param name="SheetRows">excel的文件中sheet的行数</param> 
  60.         /// <param name="ExcelVersion">导出Excel的版本</param> 
  61.         public void u_DataTableToExcel2(DataTable tempDataTable, string PathFileName, long SheetRows, string ExcelVersion) 
  62.         { 
  63.             if (tempDataTable == null
  64.             { 
  65.                 return
  66.             } 
  67.             long rowNum = tempDataTable.Rows.Count;//行数    
  68.             int columnNum = tempDataTable.Columns.Count;//列数    
  69.             Excel.Application m_xlApp = new Excel.Application(); 
  70.             m_xlApp.DisplayAlerts = false;//不显示更改提示    
  71.             m_xlApp.Visible = false
  72.             Excel.Workbooks workbooks = m_xlApp.Workbooks; 
  73.             Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); 
  74.             Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1  
  75.             try 
  76.             { 
  77.                 if (rowNum > SheetRows)//单张Sheet表格最大行数    
  78.                 { 
  79.                     long sheetRows = SheetRows;//定义每页显示的行数,行数必须小于65536    
  80.                     int scount = (int)(rowNum / sheetRows);//导出数据生成的表单数    
  81.                     if (scount * sheetRows < rowNum)//当总行数不被sheetRows整除时,经过四舍五入可能页数不准    
  82.                     { 
  83.                         scount = scount + 1; 
  84.                     } 
  85.                     for (int sc = 1; sc <= scount; sc++) 
  86.                     { 
  87.                         if (sc > 1) 
  88.                         { 
  89.                             object missing = System.Reflection.Missing.Value; 
  90.                             worksheet = (Excel.Worksheet)workbook.Worksheets.Add(missing, missing, missing, missing);//添加一个sheet    
  91.                         } 
  92.                         else 
  93.                         { 
  94.                             worksheet = (Excel.Worksheet)workbook.Worksheets[sc];//取得sheet1    
  95.                         } 
  96.                         string[,] datas = new string[sheetRows + 1, columnNum]; 
  97.                         for (int i = 0; i < columnNum; i++) //写入字段    
  98.                         { 
  99.                             datas[0, i] = tempDataTable.Columns[i].Caption;//表头信息    
  100.                         } 
  101.                         Excel.Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]); 
  102.                         range.Interior.ColorIndex = 15;//15代表灰色    
  103.                         range.Font.Bold = true
  104.                         range.Font.Size = 9; 
  105.                         int init = int.Parse(((sc - 1) * sheetRows).ToString()); 
  106.                         int r = 0; 
  107.                         int index = 0; 
  108.                         int result; 
  109.                         if (sheetRows * sc >= rowNum) 
  110.                         { 
  111.                             result = (int)rowNum; 
  112.                         } 
  113.                         else 
  114.                         { 
  115.                             result = int.Parse((sheetRows * sc).ToString()); 
  116.                         } 
  117.                         for (r = init; r < result; r++) 
  118.                         { 
  119.                             index = index + 1; 
  120.                             for (int i = 0; i < columnNum; i++) 
  121.                             { 
  122.                                 object obj = tempDataTable.Rows[r][tempDataTable.Columns[i].ToString()]; 
  123.                                 datas[index, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式   
  124.                             } 
  125.                             System.Windows.Forms.Application.DoEvents(); 
  126.                             //添加进度条    
  127.                         } 
  128.                         Excel.Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[index + 1, columnNum]); 
  129.                         fchR.Value2 = datas; 
  130.                         worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。    
  131.                         m_xlApp.WindowState = Excel.XlWindowState.xlMaximized;//Sheet表最大化    
  132.                         range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[index + 1, columnNum]); 
  133.                         //range.Interior.ColorIndex = 15;//15代表灰色    
  134.                         range.Font.Size = 9; 
  135.                         range.RowHeight = 14.25; 
  136.                         range.Borders.LineStyle = 1; 
  137.                         range.HorizontalAlignment = 1; 
  138.                     } 
  139.                 } 
  140.                 else 
  141.                 { 
  142.                     string[,] datas = new string[rowNum + 1, columnNum]; 
  143.                     for (int i = 0; i < columnNum; i++) //写入字段    
  144.                     { 
  145.                         datas[0, i] = tempDataTable.Columns[i].Caption; 
  146.                     } 
  147.                     Excel.Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]); 
  148.                     range.Interior.ColorIndex = 15;//15代表灰色    
  149.                     range.Font.Bold = true
  150.                     range.Font.Size = 9; 
  151.                     int r = 0; 
  152.                     for (r = 0; r < rowNum; r++) 
  153.                     { 
  154.                         for (int i = 0; i < columnNum; i++) 
  155.                         { 
  156.                             object obj = tempDataTable.Rows[r][tempDataTable.Columns[i].ToString()]; 
  157.                             datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式    
  158.                         } 
  159.                         System.Windows.Forms.Application.DoEvents(); 
  160.                         //添加进度条    
  161.                     } 
  162.                     Excel.Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]); 
  163.                     fchR.Value2 = datas; 
  164.                     worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。    
  165.                     m_xlApp.WindowState = Excel.XlWindowState.xlMaximized; 
  166.                     range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]); 
  167.                     //range.Interior.ColorIndex = 15;//15代表灰色    
  168.                     range.Font.Size = 9; 
  169.                     range.RowHeight = 14.25; 
  170.                     range.Borders.LineStyle = 1; 
  171.                     range.HorizontalAlignment = 1; 
  172.                 } 
  173.                 workbook.Saved = true
  174.                 switch (ExcelVersion) 
  175.                 { 
  176.                     case "2003"
  177.                         string s2003 = PathFileName + ".xls"
  178.                         object ob = System.Reflection.Missing.Value; 
  179.                         workbook.SaveAs(s2003, Excel.XlFileFormat.xlExcel8, ob, ob, ob, ob, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, ob, ob, ob, ob, ob); 
  180.                         break
  181.                     case "2007"
  182.                         string s2007 = PathFileName + ".xlsx"
  183.                         workbook.SaveCopyAs(s2007); 
  184.                         break
  185.                     defaultbreak
  186.                 } 
  187.                 KillProcess("EXCEL");//杀死excel进程 
  188.             } 
  189.             catch (Exception ex) 
  190.             { 
  191.                 MessageBox.Show("导出异常" + ex.Message, "导出异常", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
  192.             } 
  193.             finally 
  194.             { 
  195.                 KillProcess("EXCEL");//杀死excel进程 
  196.             } 
  197.         } 
  198.         #endregion 
  199.         #region 内部接口 
  200.         //作用将dt的(startindex到endindex的数据导出到filename)---用于将海量数据导出到多个excel文件 
  201.         private void u_OutExcel(DataTable dt, long startindex, long endindex, string filename, string ExcelVersion) 
  202.         { 
  203.             try 
  204.             { 
  205.                 long columnNum = dt.Columns.Count; 
  206.                 long excelRows = endindex - startindex-1; 
  207.                 Excel.Application m_xlApp = new Excel.Application(); 
  208.                 m_xlApp.DisplayAlerts = false;//不显示更改提示    
  209.                 m_xlApp.Visible = false
  210.                 Excel.Workbooks workbooks = m_xlApp.Workbooks; 
  211.                 Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); 
  212.                 Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1   
  213.                 string[,] datas = new string[excelRows + 1, columnNum]; 
  214.                 for (int i = 0; i < columnNum; i++) //写入表头字段    
  215.                 { 
  216.                     string sTitle = dt.Columns[i].ColumnName; 
  217.                     datas[0, i] = sTitle;//表头信息    
  218.                 } 
  219.                 Excel.Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]); 
  220.                 range.Interior.ColorIndex = 15;//15代表灰色    
  221.                 range.Font.Bold = true
  222.                 range.Font.Size = 9; 
  223.                 int r = 0; 
  224.                 int row = 0; 
  225.                 for (r = Convert.ToInt32(startindex); r < =endindex; r++) 
  226.                 { 
  227.                     row++; 
  228.                     for (int i = 0; i < columnNum; i++) 
  229.                     { 
  230.                         string sname = dt.Columns[i].ToString().Trim(); 
  231.                         object obj = dt.Rows[r][sname]; 
  232.                         datas[row, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式    
  233.                     } 
  234.                     System.Windows.Forms.Application.DoEvents(); 
  235.                     //添加进度条    
  236.                 } 
  237.                 Excel.Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[excelRows + 1, columnNum]); 
  238.                 fchR.Value2 = datas; 
  239.                 worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。    
  240.                 m_xlApp.WindowState = Excel.XlWindowState.xlMaximized; 
  241.                 range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[excelRows + 1, columnNum]); 
  242.                 //range.Interior.ColorIndex = 15;//15代表灰色    
  243.                 range.Font.Size = 9; 
  244.                 range.RowHeight = 14.25; 
  245.                 range.Borders.LineStyle = 1;//1边框为实线 0为excel样式 
  246.                 range.HorizontalAlignment = 1; 
  247.                 workbook.Saved = true
  248.                 switch (ExcelVersion) 
  249.                 { 
  250.                     case "2003"
  251.                         string s2003 = filename + ".xls"
  252.                         object ob = System.Reflection.Missing.Value; 
  253.                         workbook.SaveAs(s2003, Excel.XlFileFormat.xlExcel8, ob, ob, ob, ob, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, ob, ob, ob, ob, ob); 
  254.                         break
  255.                     case "2007"
  256.                         string s2007 = filename + ".xlsx"
  257.                         workbook.SaveCopyAs(s2007); 
  258.                         break
  259.                     defaultbreak
  260.                 } 
  261.                 KillProcess("EXCEL");//杀死excel进程 
  262.             } 
  263.             catch (Exception ex) 
  264.             { 
  265.                 ; 
  266.             } 
  267.         } 
  268.         //关闭进程  
  269.         private void KillProcess(string processName) 
  270.         { 
  271.             System.Diagnostics.Process myproc = new System.Diagnostics.Process(); 
  272.             try 
  273.             { 
  274.                 foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName)) 
  275.                 { 
  276.                     thisproc.Kill(); 
  277.                 } 
  278.             } 
  279.             catch 
  280.             { 
  281.             } 
  282.         } 
  283.         #endregion 
  284.         #region 附调用方法 
  285.         //Table_ToExcel outtoexcel = new Table_ToExcel(); 
  286.         //SaveFileDialog sfd = new SaveFileDialog(); 
  287.         //sfd.Filter = "Excel File|*.xlsx"; 
  288.         //sfd.FileName = DateTime.Now.ToString("yyyy.MM.dd HH.MM.SS"); 
  289.         //DataTable dt = gridControl1.DataSource as DataTable; 
  290.         //DialogResult dd = sfd.ShowDialog(this); 
  291.         //if (dd == DialogResult.OK) 
  292.         //{ 
  293.         //    outtoexcel.u_DataTableToExcel1(dt, sfd.FileName, 100, "2003"); 
  294.         //} 
  295.         #endregion 
  296.     }