C#读取Excel五种方式的体会

时间:2023-01-07 05:47:39

(1) OleDb: 用这种方法读取Excel速度还是非常的快的,但这种方式读取数据的时候不太灵活,不过可以在 DataTable 中对数据进行一些删减修改

这种方式将Excel作为一个数据源,直接用Sql语句获取数据了。所以读取之前要知道此次要读取的Sheet(当然也可以用序号,类似dt.Row[0][0]。这样倒是不需要知道Sheet)
?

  
  
 
 
  1. if (fileType == ".xls")  
  2.    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";  
  3. else 
  4.    connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";  
  5.    
  6. OleDbConnection conn new OleDbConnection(connStr);  
  7. DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { nullnullnull"TABLE" }); 

以上是读取Excel的Sheet名,xls和xlsx的连接字符串也不一样的,可以根据文件的后缀来区别。这里需要注意的一点,Excel里面只有一个Sheet,但通过这种方式读取Sheet可能会大于一个。原因已经有人在别的网站说过了,偷一下懒O(∩_∩)O,下面文段来自【cdwolfling

【在使用过程中发现取出的Sheet和实际excel不一致, 会多出不少。目前总结后有两种情况:

1. 取出的名称中,包括了XL命名管理器中的名称(参见XL2007的公式--命名管理器, 快捷键Crtl+F3);

2. 取出的名称中,包括了FilterDatabase后缀的, 这是XL用来记录Filter范围的,  参见http://www.mrexcel.com/forum/showthread.php?t=27225

对于第一点比较简单, 删除已有命名管理器中的内容即可;第二点处理起来比较麻烦, Filter删除后这些名称依然保留着,简单的做法是新增sheet然后将原sheet Copy进去】

---------------------------------

但实际情况并不能为每个Excel做以上检查【cdwolfling】也给出了过滤的方案,当时还是有点问题,本来补充了一点。总之先看代码吧

  
  
 
 
  1. for (int i = 0; i < dtSheetName.Rows.Count; i++)  
  2.  
  3. {  
  4. ?  
  5. SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];  
  6.    
  7. if (SheetName .Contains("$") && !SheetName .Replace("'""").EndsWith("$"))continue;//过滤无效SheetName完毕....  
  8.  
  9. da.SelectCommand = new OleDbCommand(String.Format(sql_F, tblName), conn);  
  10. DataSet dsItem = new DataSet();  
  11. da.Fill(dsItem, tblName);  
  12. ?  

因为读取出来无效SheetName一般情况最后一个字符都不会是$。如果SheetName有一些特殊符号,读取出来的SheetName会自动加上单引号,比如在Excel中将SheetName编辑成:MySheet(1),此时读取出来的SheetName就为:'MySheet(1)$',所以判断最后一个字符是不是$之前最好过滤一下单引号。

优点:读取方式简单、读取速度快

缺点:除了读取过程不太灵活之外,这种读取方式还有个弊端就是,当Excel数据量很大时。会非常占用内存,当内存不够时会抛出内存溢出的异常。

不过一般情况下还是非常不错的

读取Excel完整代码:

  
  
 
 
  1. /// <summary>  
  2.         /// 读取Excel文件到DataSet中  
  3.         /// </summary>  
  4.         /// <param name="filePath">文件路径</param>  
  5.         /// <returns></returns>  
  6.         public static DataSet ToDataTable(string filePath)  
  7.         {  
  8.             string connStr = "";             
  9.             string fileType = System.IO.Path.GetExtension(fileName);  
  10.             if (string.IsNullOrEmpty(fileType)) return null;  
  11.    
  12.             if (fileType == ".xls")  
  13.                 connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath+ ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";  
  14.             else 
  15.                 connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath+ ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";  
  16.             string sql_F = "Select * FROM [{0}]";  
  17.    
  18.             OleDbConnection conn = null;  
  19.             OleDbDataAdapter da = null;  
  20.             DataTable dtSheetName= null;  
  21.    
  22.             DataSet ds = new DataSet();  
  23.             try 
  24.             {  
  25.                 // 初始化连接,并打开  
  26.                 conn = new OleDbConnection(connStr);  
  27.                 conn.Open();  
  28.    
  29.                 // 获取数据源的表定义元数据                         
  30.                 string SheetName = "";  
  31.                 dtSheetName= conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { nullnullnull"TABLE" });  
  32.    
  33.                 // 初始化适配器  
  34.                 da = new OleDbDataAdapter();  
  35.                 for (int i = 0; i < dtSheetName.Rows.Count; i++)  
  36.                 {  
  37.                     SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];  
  38.    
  39.                     if (SheetName .Contains("$") && !SheetName .Replace("'""").EndsWith("$"))  
  40.                     {  
  41.                         continue;  
  42.                     }  
  43.    
  44.                     da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName ), conn);  
  45.                     DataSet dsItem = new DataSet();  
  46.                     da.Fill(dsItem, tblName);  
  47.    
  48.                     ds.Tables.Add(dsItem.Tables[0].Copy());  
  49.                 }  
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.             }  
  54.             finally 
  55.             {  
  56.                 // 关闭连接  
  57.                 if (conn.State == ConnectionState.Open)  
  58.                 {  
  59.                     conn.Close();  
  60.                     da.Dispose();  
  61.                     conn.Dispose();  
  62.                 }  
  63.             }  
  64.             return ds;  
  65.         } 

(2):Com组件的方式读取Excel

这种方式需要先引用 Microsoft.Office.Interop.Excel 。首选说下这种方式的优缺点

优点:可以非常灵活的读取Excel中的数据

缺点:如果是Web站点部署在IIS上时,还需要服务器机子已安装了Excel,有时候还需要为配置IIS权限。最重要的一点因为是基于单元格方式读取的,所以数据很慢(曾做过试验,直接读取千行、200多列的文件,直接读取耗时15分钟。即使采用多线程分段读取来提高CPU的利用率也需要8分钟。PS:CPU I3)

需要读取大文件的的童鞋们慎重。。。

附上单线程和多线程读取类:

  
  
 
 
  1. public class ExcelOptions  
  2.     {  
  3.         private Stopwatch wath = new Stopwatch();  
  4.    
  5.         /// <summary>  
  6.         /// 使用COM读取Excel  
  7.         /// </summary>  
  8.         /// <param name="excelFilePath">路径</param>  
  9.         /// <returns>DataTabel</returns>  
  10.         public System.Data.DataTable GetExcelData(string excelFilePath)  
  11.         {  
  12.             Excel.Application app = new Excel.Application();  
  13.             Excel.Sheets sheets;  
  14.             Excel.Workbook workbook = null;  
  15.             object oMissiong = System.Reflection.Missing.Value;  
  16.             System.Data.DataTable dt = new System.Data.DataTable();  
  17.    
  18.             wath.Start();  
  19.    
  20.             try 
  21.             {  
  22.                 if (app == null)  
  23.                 {  
  24.                     return null;  
  25.                 }  
  26.    
  27.                 workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);  
  28.    
  29.                 //将数据读入到DataTable中——Start    
  30.    
  31.                 sheets = workbook.Worksheets;  
  32.                 Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表  
  33.                 if (worksheet == null)  
  34.                     return null;  
  35.    
  36.                 string cellContent;  
  37.                 int iRowCount = worksheet.UsedRange.Rows.Count;  
  38.                 int iColCount = worksheet.UsedRange.Columns.Count;  
  39.                 Excel.Range range;  
  40.    
  41.                 //负责列头Start  
  42.                 DataColumn dc;  
  43.                 int ColumnID = 1;  
  44.                 range = (Excel.Range)worksheet.Cells[1, 1];  
  45.                 while (range.Text.ToString().Trim() != "")  
  46.                 {  
  47.                     dc = new DataColumn();  
  48.                     dc.DataType = System.Type.GetType("System.String");  
  49.                     dc.ColumnName = range.Text.ToString().Trim();  
  50.                     dt.Columns.Add(dc);  
  51.    
  52.                     range = (Excel.Range)worksheet.Cells[1, ++ColumnID];  
  53.                 }  
  54.                 //End  
  55.    
  56.                 for (int iRow = 2; iRow <= iRowCount; iRow++)  
  57.                 {  
  58.                     DataRow dr = dt.NewRow();  
  59.    
  60.                     for (int iCol = 1; iCol <= iColCount; iCol++)  
  61.                     {  
  62.                         range = (Excel.Range)worksheet.Cells[iRow, iCol];  
  63.    
  64.                         cellContent = (range.Value2 == null) ? "" : range.Text.ToString();  
  65.    
  66.                         //if (iRow == 1)  
  67.                         //{  
  68.                         //    dt.Columns.Add(cellContent);  
  69.                         //}  
  70.                         //else  
  71.                         //{  
  72.                             dr[iCol - 1] = cellContent;  
  73.                         //}  
  74.                     }  
  75.    
  76.                     //if (iRow != 1)  
  77.                     dt.Rows.Add(dr);  
  78.                 }  
  79.    
  80.                 wath.Stop();  
  81.                 TimeSpan ts = wath.Elapsed;  
  82.    
  83.                 //将数据读入到DataTable中——End  
  84.                 return dt;  
  85.             }  
  86.             catch 
  87.             {  
  88.                    
  89.                 return null;  
  90.             }  
  91.             finally 
  92.             {  
  93.                 workbook.Close(false, oMissiong, oMissiong);  
  94.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);  
  95.                 workbook = null;  
  96.                 app.Workbooks.Close();  
  97.                 app.Quit();  
  98.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(app);  
  99.                 app = null;  
  100.                 GC.Collect();  
  101.                 GC.WaitForPendingFinalizers();  
  102.             }  
  103.         }  
  104.    
  105.    
  106.         /// <summary>  
  107.         /// 使用COM,多线程读取Excel(1 主线程、4 副线程)  
  108.         /// </summary>  
  109.         /// <param name="excelFilePath">路径</param>  
  110.         /// <returns>DataTabel</returns>  
  111.         public System.Data.DataTable ThreadReadExcel(string excelFilePath)  
  112.         {  
  113.             Excel.Application app = new Excel.Application();  
  114.             Excel.Sheets sheets = null;  
  115.             Excel.Workbook workbook = null;  
  116.             object oMissiong = System.Reflection.Missing.Value;  
  117.             System.Data.DataTable dt = new System.Data.DataTable();  
  118.    
  119.             wath.Start();  
  120.    
  121.             try 
  122.             {  
  123.                 if (app == null)  
  124.                 {  
  125.                     return null;  
  126.                 }  
  127.    
  128.                 workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);  
  129.    
  130.                 //将数据读入到DataTable中——Start    
  131.                 sheets = workbook.Worksheets;  
  132.                 Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表  
  133.                 if (worksheet == null)  
  134.                     return null;  
  135.    
  136.                 string cellContent;  
  137.                 int iRowCount = worksheet.UsedRange.Rows.Count;  
  138.                 int iColCount = worksheet.UsedRange.Columns.Count;  
  139.                 Excel.Range range;  
  140.    
  141.                 //负责列头Start  
  142.                 DataColumn dc;  
  143.                 int ColumnID = 1;  
  144.                 range = (Excel.Range)worksheet.Cells[1, 1];  
  145.                 //while (range.Text.ToString().Trim() != "")  
  146.                 while (iColCount >= ColumnID)  
  147.                 {  
  148.                     dc = new DataColumn();  
  149.                     dc.DataType = System.Type.GetType("System.String");  
  150.    
  151.                     string strNewColumnName = range.Text.ToString().Trim();  
  152.                     if (strNewColumnName.Length == 0) strNewColumnName = "_1";  
  153.                     //判断列名是否重复  
  154.                     for (int i = 1; i < ColumnID; i++)  
  155.                     {  
  156.                         if (dt.Columns[i - 1].ColumnName == strNewColumnName)  
  157.                             strNewColumnName = strNewColumnName + "_1";  
  158.                     }  
  159.    
  160.                     dc.ColumnName = strNewColumnName;  
  161.                     dt.Columns.Add(dc);  
  162.    
  163.                     range = (Excel.Range)worksheet.Cells[1, ++ColumnID];  
  164.                 }  
  165.                 //End  
  166.    
  167.                 //数据大于500条,使用多进程进行读取数据  
  168.                 if (iRowCount - 1 > 500)  
  169.                 {  
  170.                     //开始多线程读取数据  
  171.                     //新建线程  
  172.                     int b2 = (iRowCount - 1) / 10;  
  173.                     DataTable dt1 = new DataTable("dt1");  
  174.                     dt1 = dt.Clone();  
  175.                     SheetOptions sheet1thread = new SheetOptions(worksheet, iColCount, 2, b2 + 1, dt1);  
  176.                     Thread othread1 = new Thread(new ThreadStart(sheet1thread.SheetToDataTable));  
  177.                     othread1.Start();  
  178.    
  179.                     //阻塞 1 毫秒,保证第一个读取 dt1  
  180.                     Thread.Sleep(1);  
  181.    
  182.                     DataTable dt2 = new DataTable("dt2");  
  183.                     dt2 = dt.Clone();  
  184.                     SheetOptions sheet2thread = new SheetOptions(worksheet, iColCount, b2 + 2, b2 * 2 + 1, dt2);  
  185.                     Thread othread2 = new Thread(new ThreadStart(sheet2thread.SheetToDataTable));  
  186.                     othread2.Start();  
  187.    
  188.                     DataTable dt3 = new DataTable("dt3");  
  189.                     dt3 = dt.Clone();  
  190.                     SheetOptions sheet3thread = new SheetOptions(worksheet, iColCount, b2 * 2 + 2, b2 * 3 + 1, dt3);  
  191.                     Thread othread3 = new Thread(new ThreadStart(sheet3thread.SheetToDataTable));  
  192.                     othread3.Start();  
  193.    
  194.                     DataTable dt4 = new DataTable("dt4");  
  195.                     dt4 = dt.Clone();  
  196.                     SheetOptions sheet4thread = new SheetOptions(worksheet, iColCount, b2 * 3 + 2, b2 * 4 + 1, dt4);  
  197.                     Thread othread4 = new Thread(new ThreadStart(sheet4thread.SheetToDataTable));  
  198.                     othread4.Start();  
  199.    
  200.                     //主线程读取剩余数据  
  201.                     for (int iRow = b2 * 4 + 2; iRow <= iRowCount; iRow++)  
  202.                     {  
  203.                         DataRow dr = dt.NewRow();  
  204.                         for (int iCol = 1; iCol <= iColCount; iCol++)  
  205.                         {  
  206.                             range = (Excel.Range)worksheet.Cells[iRow, iCol];  
  207.                             cellContent = (range.Value2 == null) ? "" : range.Text.ToString();  
  208.                             dr[iCol - 1] = cellContent;  
  209.                         }  
  210.                         dt.Rows.Add(dr);  
  211.                     }  
  212.    
  213.                     othread1.Join();  
  214.                     othread2.Join();  
  215.                     othread3.Join();  
  216.                     othread4.Join();  
  217.    
  218.                     //将多个线程读取出来的数据追加至 dt1 后面  
  219.                     foreach (DataRow dr in dt.Rows)  
  220.                         dt1.Rows.Add(dr.ItemArray);  
  221.                     dt.Clear();  
  222.                     dt.Dispose();  
  223.    
  224.                     foreach (DataRow dr in dt2.Rows)  
  225.                         dt1.Rows.Add(dr.ItemArray);  
  226.                     dt2.Clear();  
  227.                     dt2.Dispose();  
  228.    
  229.                     foreach (DataRow dr in dt3.Rows)  
  230.                         dt1.Rows.Add(dr.ItemArray);  
  231.                     dt3.Clear();  
  232.                     dt3.Dispose();  
  233.    
  234.                     foreach (DataRow dr in dt4.Rows)  
  235.                         dt1.Rows.Add(dr.ItemArray);  
  236.                     dt4.Clear();  
  237.                     dt4.Dispose();  
  238.    
  239.                     return dt1;  
  240.                 }  
  241.                 else 
  242.                 {  
  243.                     for (int iRow = 2; iRow <= iRowCount; iRow++)  
  244.                     {  
  245.                         DataRow dr = dt.NewRow();  
  246.                         for (int iCol = 1; iCol <= iColCount; iCol++)  
  247.                         {  
  248.                             range = (Excel.Range)worksheet.Cells[iRow, iCol];  
  249.                             cellContent = (range.Value2 == null) ? "" : range.Text.ToString();  
  250.                             dr[iCol - 1] = cellContent;  
  251.                         }  
  252.                         dt.Rows.Add(dr);  
  253.                     }  
  254.                 }  
  255.    
  256.                 wath.Stop();  
  257.                 TimeSpan ts = wath.Elapsed;  
  258.                 //将数据读入到DataTable中——End  
  259.                 return dt;  
  260.             }  
  261.             catch 
  262.             {  
  263.    
  264.                 return null;  
  265.             }  
  266.             finally 
  267.             {  
  268.                 workbook.Close(false, oMissiong, oMissiong);  
  269.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);  
  270.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);  
  271.                 workbook = null;  
  272.                 app.Workbooks.Close();  
  273.                 app.Quit();  
  274.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(app);  
  275.                 app = null;  
  276.                 GC.Collect();  
  277.                 GC.WaitForPendingFinalizers();  
  278.                    
  279.                 /*  
  280.                 object objmissing = System.Reflection.Missing.Value;  
  281.    
  282. Excel.ApplicationClass application = new ApplicationClass();  
  283. Excel.Workbook book = application.Workbooks.Add(objmissing);  
  284. Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets.Add(objmissing,objmissing,objmissing,objmissing);  
  285.    
  286. //操作过程 ^&%&×&……&%&&……  
  287.    
  288. //释放  
  289. sheet.SaveAs(path,objmissing,objmissing,objmissing,objmissing,objmissing,objmissing,objmissing,objmissing);  
  290. System.Runtime.InteropServices.Marshal.ReleaseComObject((object)sheet);  
  291. System.Runtime.InteropServices.Marshal.ReleaseComObject((object)book);  
  292. application.Quit();  
  293. System.Runtime.InteropServices.Marshal.ReleaseComObject((object)application);  
  294. System.GC.Collect();  
  295.                  */ 
  296.             }  
  297.         }  
  298.    
  299.    
  300.         /// <summary>  
  301.         /// 删除Excel行  
  302.         /// </summary>  
  303.         /// <param name="excelFilePath">Excel路径</param>  
  304.         /// <param name="rowStart">开始行</param>  
  305.         /// <param name="rowEnd">结束行</param>  
  306.         /// <param name="designationRow">指定行</param>  
  307.         /// <returns></returns>  
  308.         public string DeleteRows(string excelFilePath, int rowStart, int rowEnd, int designationRow)  
  309.         {  
  310.             string result = "";  
  311.             Excel.Application app = new Excel.Application();  
  312.             Excel.Sheets sheets;  
  313.             Excel.Workbook workbook = null;  
  314.             object oMissiong = System.Reflection.Missing.Value;  
  315.             try 
  316.             {  
  317.                 if (app == null)  
  318.                 {  
  319.                     return "分段读取Excel失败";  
  320.                 }  
  321.    
  322.                 workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);  
  323.                 sheets = workbook.Worksheets;  
  324.                 Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表  
  325.                 if (worksheet == null)  
  326.                     return result;  
  327.                 Excel.Range range;  
  328.    
  329.                 //先删除指定行,一般为列描述  
  330.                 if (designationRow != -1)  
  331.                 {  
  332.                     range = (Excel.Range)worksheet.Rows[designationRow, oMissiong];  
  333.                     range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);  
  334.                 }  
  335.                 Stopwatch sw = new Stopwatch();  
  336.                 sw.Start();  
  337.    
  338.                 int i = rowStart;  
  339.                 for (int iRow = rowStart; iRow <= rowEnd; iRow++, i++)  
  340.                 {  
  341.                     range = (Excel.Range)worksheet.Rows[rowStart, oMissiong];  
  342.                     range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);  
  343.                 }  
  344.    
  345.                 sw.Stop();  
  346.                 TimeSpan ts = sw.Elapsed;  
  347.                 workbook.Save();  
  348.    
  349.                 //将数据读入到DataTable中——End  
  350.                 return result;  
  351.             }  
  352.             catch 
  353.             {  
  354.    
  355.                 return "分段读取Excel失败";  
  356.             }  
  357.             finally 
  358.             {  
  359.                 workbook.Close(false, oMissiong, oMissiong);  
  360.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);  
  361.                 workbook = null;  
  362.                 app.Workbooks.Close();  
  363.                 app.Quit();  
  364.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(app);  
  365.                 app = null;  
  366.                 GC.Collect();  
  367.                 GC.WaitForPendingFinalizers();  
  368.             }  
  369.         }  
  370.    
  371.         public void ToExcelSheet(DataSet ds, string fileName)  
  372.         {  
  373.             Excel.Application appExcel = new Excel.Application();  
  374.             Excel.Workbook workbookData = null;  
  375.             Excel.Worksheet worksheetData;  
  376.             Excel.Range range;  
  377.             try 
  378.             {  
  379.                 workbookData = appExcel.Workbooks.Add(System.Reflection.Missing.Value);  
  380.                 appExcel.DisplayAlerts = false;//不显示警告  
  381.                 //xlApp.Visible = true;//excel是否可见  
  382.                 //  
  383.                 //for (int i = workbookData.Worksheets.Count; i > 0; i--)  
  384.                 //{  
  385.                 //    Microsoft.Office.Interop.Excel.Worksheet oWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbookData.Worksheets.get_Item(i);  
  386.                 //    oWorksheet.Select();  
  387.                 //    oWorksheet.Delete();  
  388.                 //}  
  389.    
  390.                 for (int k = 0; k < ds.Tables.Count; k++)  
  391.                 {  
  392.                     worksheetData = (Excel.Worksheet)workbookData.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);  
  393.                     // testnum--;  
  394.                     if (ds.Tables[k] != null)  
  395.                     {  
  396.                         worksheetData.Name = ds.Tables[k].TableName;  
  397.                         //写入标题  
  398.                         for (int i = 0; i < ds.Tables[k].Columns.Count; i++)  
  399.                         {  
  400.                             worksheetData.Cells[1, i + 1] = ds.Tables[k].Columns[i].ColumnName;  
  401.                             range = (Excel.Range)worksheetData.Cells[1, i + 1];  
  402.                             //range.Interior.ColorIndex = 15;  
  403.                             range.Font.Bold = true;  
  404.                             range.NumberFormatLocal = "@";//文本格式  
  405.                             range.EntireColumn.AutoFit();//自动调整列宽  
  406.                             // range.WrapText = true; //文本自动换行    
  407.                             range.ColumnWidth = 15;  
  408.                         }  
  409.                         //写入数值  
  410.                         for (int r = 0; r < ds.Tables[k].Rows.Count; r++)  
  411.                         {  
  412.                             for (int i = 0; i < ds.Tables[k].Columns.Count; i++)  
  413.                             {  
  414.                                 worksheetData.Cells[r + 2, i + 1] = ds.Tables[k].Rows[r][i];  
  415.                                 //Range myrange = worksheetData.get_Range(worksheetData.Cells[r + 2, i + 1], worksheetData.Cells[r + 3, i + 2]);  
  416.                                 //myrange.NumberFormatLocal = "@";//文本格式  
  417.                                 //// myrange.EntireColumn.AutoFit();//自动调整列宽  
  418.                                 ////   myrange.WrapText = true; //文本自动换行    
  419.                                 //myrange.ColumnWidth = 15;  
  420.                             }  
  421.                             //  rowRead++;  
  422.                             //System.Windows.Forms.Application.DoEvents();  
  423.                         }  
  424.                     }  
  425.                     worksheetData.Columns.EntireColumn.AutoFit();  
  426.                     workbookData.Saved = true;  
  427.                 }  
  428.             }  
  429.             catch (Exception ex) { }  
  430.             finally 
  431.             {  
  432.                 workbookData.SaveCopyAs(fileName);  
  433.                 workbookData.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);  
  434.                 appExcel.Quit();  
  435.                 GC.Collect();  
  436.             }  
  437.         }  
  438.        
  439.     } 

(3)NPOI方式读取Excel,NPOI是一组开源的组件,类似Java的 POI。包括:NPOI、NPOI.HPSF、NPOI.HSSF、NPOI.HSSF.UserModel、NPOI.POIFS、NPOI.Util,下载的时候别只下一个噢

优点:读取Excel速度较快,读取方式操作灵活性

缺点:只支持03的Excel,xlsx的无法读取。由于这点,使用这种方式的人不多啊,没理由要求客户使用03版Excel吧,再说03版Excel对于行数还有限制,只支持65536行。

(听他们的开发人员说会在2012年底推出新版,支持xlsx的读取。但一直很忙没时间去关注这个事情,有兴趣的同学可以瞧瞧去)

NPOI读取Excel类:

  
  
 
 
  1. using System;  
  2. using System.Data;  
  3. using System.IO;  
  4. using System.Web;  
  5. using NPOI;  
  6. using NPOI.HPSF;  
  7. using NPOI.HSSF;  
  8. using NPOI.HSSF.UserModel;  
  9. using NPOI.POIFS;  
  10. using NPOI.Util;  
  11. using System.Text;  
  12. using System.Configuration;  
  13.    
  14. public class NPOIHelper  
  15. {  
  16.     private static int ExcelMaxRow = Convert.ToInt32(ConfigurationManager.AppSettings["ExcelMaxRow"]);  
  17.     /// <summary>  
  18.     /// 由DataSet导出Excel  
  19.     /// </summary>  
  20.     /// <param name="sourceTable">要导出数据的DataTable</param>     
  21.     /// <param name="sheetName">工作表名称</param>  
  22.     /// <returns>Excel工作表</returns>     
  23.     private static Stream ExportDataSetToExcel(DataSet sourceDs)  
  24.     {  
  25.         HSSFWorkbook workbook = new HSSFWorkbook();  
  26.         MemoryStream ms = new MemoryStream();  
  27.    
  28.         for (int i = 0; i < sourceDs.Tables.Count; i++)  
  29.         {  
  30.             HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(sourceDs.Tables[i].TableName);  
  31.             HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);  
  32.             // handling header.             
  33.             foreach (DataColumn column in sourceDs.Tables[i].Columns)  
  34.                 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);  
  35.             // handling value.             
  36.             int rowIndex = 1;  
  37.             foreach (DataRow row in sourceDs.Tables[i].Rows)  
  38.             {  
  39.                 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);  
  40.                 foreach (DataColumn column in sourceDs.Tables[i].Columns)  
  41.                 {  
  42.                     dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());  
  43.                 }  
  44.                 rowIndex++;  
  45.             }  
  46.         }  
  47.         workbook.Write(ms);  
  48.         ms.Flush();  
  49.         ms.Position = 0;  
  50.         workbook = null;  
  51.         return ms;  
  52.     }  
  53.     /// <summary>  
  54.     /// 由DataSet导出Excel  
  55.     /// </summary>    
  56.     /// <param name="sourceTable">要导出数据的DataTable</param>  
  57.     /// <param name="fileName">指定Excel工作表名称</param>  
  58.     /// <returns>Excel工作表</returns>     
  59.     public static void ExportDataSetToExcel(DataSet sourceDs, string fileName)  
  60.     {  
  61.         //检查是否有Table数量超过65325  
  62.         for (int t = 0; t < sourceDs.Tables.Count; t++)  
  63.         {  
  64.             if (sourceDs.Tables[t].Rows.Count > ExcelMaxRow)  
  65.             {  
  66.                 DataSet ds = GetdtGroup(sourceDs.Tables[t].Copy());  
  67.                 sourceDs.Tables.RemoveAt(t);  
  68.                 //将得到的ds插入 sourceDs中  
  69.                 for (int g = 0; g < ds.Tables.Count; g++)  
  70.                 {  
  71.                     DataTable dt = ds.Tables[g].Copy();  
  72.                     sourceDs.Tables.Add(dt);  
  73.                 }  
  74.                 t--;  
  75.             }  
  76.         }  
  77.    
  78.         MemoryStream ms = ExportDataSetToExcel(sourceDs) as MemoryStream;  
  79.         HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename=" + fileName);  
  80.         HttpContext.Current.Response.BinaryWrite(ms.ToArray());  
  81.         HttpContext.Current.ApplicationInstance.CompleteRequest();  
  82.         //HttpContext.Current.Response.End();  
  83.         ms.Close();  
  84.         ms = null;  
  85.     }  
  86.     /// <summary>  
  87.     /// 由DataTable导出Excel  
  88.     /// </summary>  
  89.     /// <param name="sourceTable">要导出数据的DataTable</param>  
  90.     /// <returns>Excel工作表</returns>     
  91.     private static Stream ExportDataTableToExcel(DataTable sourceTable)  
  92.     {  
  93.         HSSFWorkbook workbook = new HSSFWorkbook();  
  94.         MemoryStream ms = new MemoryStream();  
  95.         HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(sourceTable.TableName);  
  96.         HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);  
  97.         // handling header.       
  98.         foreach (DataColumn column in sourceTable.Columns)  
  99.             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);  
  100.         // handling value.       
  101.         int rowIndex = 1;  
  102.         foreach (DataRow row in sourceTable.Rows)  
  103.         {  
  104.             HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);  
  105.             foreach (DataColumn column in sourceTable.Columns)  
  106.             {  
  107.                 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());  
  108.             }  
  109.             rowIndex++;  
  110.         }  
  111.         workbook.Write(ms);  
  112.         ms.Flush();  
  113.         ms.Position = 0;  
  114.         sheet = null;  
  115.         headerRow = null;  
  116.         workbook = null;  
  117.         return ms;  
  118.     }  
  119.     /// <summary>  
  120.     /// 由DataTable导出Excel  
  121.     /// </summary>  
  122.     /// <param name="sourceTable">要导出数据的DataTable</param>  
  123.     /// <param name="fileName">指定Excel工作表名称</param>  
  124.     /// <returns>Excel工作表</returns>  
  125.     public static void ExportDataTableToExcel(DataTable sourceTable, string fileName)  
  126.     {  
  127.         //如数据超过65325则分成多个Table导出  
  128.         if (sourceTable.Rows.Count > ExcelMaxRow)  
  129.         {  
  130.             DataSet ds = GetdtGroup(sourceTable);  
  131.             //导出DataSet  
  132.             ExportDataSetToExcel(ds, fileName);  
  133.         }  
  134.         else 
  135.         {  
  136.             MemoryStream ms = ExportDataTableToExcel(sourceTable) as MemoryStream;  
  137.             HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename=" + fileName);  
  138.             HttpContext.Current.Response.BinaryWrite(ms.ToArray());  
  139.             HttpContext.Current.ApplicationInstance.CompleteRequest();  
  140.             //HttpContext.Current.Response.End();  
  141.             ms.Close();  
  142.             ms = null;  
  143.         }  
  144.     }  
  145.    
  146.     /// <summary>  
  147.     /// 传入行数超过65325的Table,返回DataSet  
  148.     /// </summary>  
  149.     /// <param name="dt"></param>  
  150.     /// <returns></returns>  
  151.     public static DataSet GetdtGroup(DataTable dt)  
  152.     {  
  153.         string tablename = dt.TableName;  
  154.    
  155.         DataSet ds = new DataSet();  
  156.         ds.Tables.Add(dt);  
  157.    
  158.         double n = dt.Rows.Count / Convert.ToDouble(ExcelMaxRow);  
  159.    
  160.         //创建表  
  161.         for (int i = 1; i < n; i++)  
  162.         {  
  163.             DataTable dtAdd = dt.Clone();  
  164.             dtAdd.TableName = tablename + "_" + i.ToString();  
  165.             ds.Tables.Add(dtAdd);  
  166.         }  
  167.    
  168.         //分解数据  
  169.         for (int i = 1; i < ds.Tables.Count; i++)  
  170.         {  
  171.             //新表行数达到最大 或 基表数量不足  
  172.             while (ds.Tables[i].Rows.Count != ExcelMaxRow && ds.Tables[0].Rows.Count != ExcelMaxRow)  
  173.             {  
  174.                 ds.Tables[i].Rows.Add(ds.Tables[0].Rows[ExcelMaxRow].ItemArray);  
  175.                 ds.Tables[0].Rows.RemoveAt(ExcelMaxRow);  
  176.    
  177.             }  
  178.         }  
  179.    
  180.         return ds;  
  181.     }  
  182.    
  183.     /// <summary>  
  184.     /// 由DataTable导出Excel  
  185.     /// </summary>  
  186.     /// <param name="sourceTable">要导出数据的DataTable</param>  
  187.     /// <param name="fileName">指定Excel工作表名称</param>  
  188.     /// <returns>Excel工作表</returns>  
  189.     public static void ExportDataTableToExcelModel(DataTable sourceTable, string modelpath, string modelName, string fileName, string sheetName)  
  190.     {  
  191.         int rowIndex = 2;//从第二行开始,因为前两行是模板里面的内容  
  192.         int colIndex = 0;  
  193.         FileStream file = new FileStream(modelpath + modelName + ".xls", FileMode.Open, FileAccess.Read);//读入excel模板  
  194.         HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);  
  195.         HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.GetSheet("Sheet1");  
  196.         sheet1.GetRow(0).GetCell(0).SetCellValue("excelTitle");      //设置表头  
  197.         foreach (DataRow row in sourceTable.Rows)  
  198.         {   //双循环写入sourceTable中的数据  
  199.             rowIndex++;  
  200.             colIndex = 0;  
  201.             HSSFRow xlsrow = (HSSFRow)sheet1.CreateRow(rowIndex);  
  202.             foreach (DataColumn col in sourceTable.Columns)  
  203.             {  
  204.                 xlsrow.CreateCell(colIndex).SetCellValue(row[col.ColumnName].ToString());  
  205.                 colIndex++;  
  206.             }  
  207.         }  
  208.         sheet1.ForceFormulaRecalculation = true;  
  209.         FileStream fileS = new FileStream(modelpath + fileName + ".xls", FileMode.Create);//保存  
  210.         hssfworkbook.Write(fileS);  
  211.         fileS.Close();  
  212.         file.Close();  
  213.     }  

本文过长,4,5放在下一篇文章进行介绍!

4)

5)