优点:能够非常灵活的读取Excel中的数据,用户可以灵活的调用各种函数进行处理。
缺点:基于单元格的处理,读取速度较慢,对于数据量较大的文件最好不要使用此种方式读取。
需要添加相应的DLL引用,必须存在此引用才可使用,如果是Web站点部署在IIS上时,还需要服务器机子已安装了Excel,有时候还需要为配置IIS权限。
读取代码如下:
- private Stopwatch wath = new Stopwatch(); /// <summary>
- /// 使用COM读取Excel /// </summary>
- /// <param name="excelFilePath">路径</param> /// <returns>DataTabel</returns>
- public System.Data.DataTable GetExcelData(string excelFilePath) {
- Excel.Application app = new Excel.Application(); Excel.Sheets sheets;
- Excel.Workbook workbook = null; object oMissiong = System.Reflection.Missing.Value;
- System.Data.DataTable dt = new System.Data.DataTable(); wath.Start();
- try {
- if (app == null) {
- return null; }
- workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
- //将数据读入到DataTable中——Start sheets = workbook.Worksheets;
- Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表 if (worksheet == null)
- return null; string cellContent;
- int iRowCount = worksheet.UsedRange.Rows.Count; int iColCount = worksheet.UsedRange.Columns.Count;
- Excel.Range range; //负责列头Start
- DataColumn dc; int ColumnID = 1;
- range = (Excel.Range)worksheet.Cells[1, 1]; while (range.Text.ToString().Trim() != "")
- { dc = new DataColumn();
- dc.DataType = System.Type.GetType("System.String"); dc.ColumnName = range.Text.ToString().Trim();










