日期:2014-05-18 浏览次数:21208 次
DataSet ds = GetWorkbook(Application.StartupPath + @"\App_Data\Book1.xls"); public static DataSet GetWorkbook(string filename) { DataSet ds = new DataSet(); Excel.Application app = new Excel.Application(); //初始化Excel对象 app.Visible = false; app.DisplayAlerts = false; object missing = System.Reflection.Missing.Value; Excel.Workbook wb;// = app.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); try { wb = app.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); } catch (Exception ex) { MessageBox.Show(ex.ToString()); throw; } foreach (Excel.Worksheet ws in wb.Sheets) { ds.Tables.Add(GetWorksheet(ws)); } app.Workbooks.Close(); app.Quit(); return ds; } public static DataTable GetWorksheet(Excel.Worksheet ws) { DataTable dt = new DataTable(); dt.TableName = ws.Name; int row = ws.UsedRange.Rows.Count + 1; int col = ws.UsedRange.Columns.Count + 1; for (int c = 1; c < col; c++) { dt.Columns.Add("F" + c); } for (int r = 1; r < row; r++) { DataRow newRow = dt.NewRow(); for (int c = 1; c < col; c++) { newRow[c - 1] = ((Excel.Range)ws.Cells[r, c]).Value2; //问题是不是出在这里,请问怎么解决呢 } dt.Rows.Add(newRow); } return dt; }