提供兩種方法:一個是直接開啟excel檔案,然後逐行讀取,速度較慢;還有一種方法是通過OleDb串連,把excel檔案作為資料來源來讀取
方法一:這種直接讀取儲存格的方法釋放很重要。
Excel.Application excel = null;
Excel.Workbooks wbs = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Range range1 = null;
object Nothing = System.Reflection.Missing.Value;
try
{
excel = new Excel.Application();
excel.UserControl = true;
excel.DisplayAlerts = false;
excel.Application.Workbooks.Open(this.FilePath,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing ) ;
wbs = excel.Workbooks;
wb = wbs[1];
ws = (Excel.Worksheet)wb.Worksheets["Sheet2"];
int rowCount = ws.UsedRange.Rows.Count;
int colCount = ws.UsedRange.Columns.Count;
if (rowCount <= 0)
throw new InvalidFormatException("檔案中沒有資料記錄");
if (colCount < 4 )
throw new InvalidFormatException("欄位個數不對");
for (int i = 0;i {
this.rowNo = i + 1;
object[] row = new object[4];
for (int j = 0;j<4;j++)
{
range1 = ws.get_Range(ws.Cells[i+2,j+1],ws.Cells[i+2,j+1]);
row[j] = range1.Value;
if (row[0] == null)
{
this.isNullRecord++;
break;
}
}
if (this.isNullRecord > 0)
continue;
DataRow dataRow = this.readExcel(row);
if (this.isNullRecord == 1)
continue;
if (this.verifyData(dataRow) == false)
errFlag++;
this.updateTableCurr(dataRow);
}
}
finally
{
if (excel != null)
{
if (wbs != null)
{
if (wb != null)
{
if (ws != null)
{
if (range1 != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range1);
range1 = null;
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
ws = null;
}
wb.Close(false,Nothing,Nothing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
wb = null;
}
wbs.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbs);
wbs = null;
}
excel.Application.Workbooks.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
excel = null;
GC.Collect();
}
}
方法二:這裡是fill進dataset,也可以返回OleDbDataReader來逐行讀,資料較快
註:這種方法容易把混合型的欄位作為null值讀取進來,解決辦法是改造連接字串
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Erp1912.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
通過Imex=1來把混合型作為文本型讀取,避免null值,詳細請見http://www.connectionstrings.com/
private DataSet importExcelToDataSet(string FilePath)
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",strConn);
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet);
}
catch(Exception ex)
{
throw new InvalidFormatException("該Excel檔案的工作表的名字不正確," + ex.Message);
}
return myDataSet;
}