導入Excel的操作是非常常見的操作,可以使用Aspose.Cell、APOI、MyXls、OLEDB、Excel VBA等操作Excel文件,從而實現數據的導入,在導入數據的時候,如果是強類型的數據,那么這幾種方式好像都表現差不多,正常操作能夠導入數據。如果是非強類型的數據,那么就需要特別注意了,一般情況下,導入的DataTable數據列的類型是以第一行內容作為確定列類型的,本文介紹利用Aspose.Cell控件導入Excel非強類型的數據的操作。
什么是強類型的數據呢,就是在Excel表格中,除了第一列名外,他們的數據格式都一樣的,如下所示。
如果使用C#導入到Winform界面中,那么數據顯示效果如下所示。從這里可以看到,這些數據都是遵循一定的格式,名字為字符串,年齡為數值。
使用OLEDB方式導入Excel數據的代碼如下所示。
try { myDs.Tables.Clear(); myDs.Clear(); this.gridControl1.DataSource = null; string connectString = string.Format(connectionStringFormat, this.txtFilePath.Text); string firstSheet = ExcelHelper.GetExcelFirstTableName(connectString); OleDbConnection cnnxls = new OleDbConnection(connectString); OleDbDataAdapter myDa = new OleDbDataAdapter(string.Format("select * from [{0}]", firstSheet), cnnxls); myDa.Fill(myDs, "【導入表】"); this.gridControl1.DataSource = myDs.Tables[0]; this.gridView1.PopulateColumns(); } catch (Exception ex) { LogHelper.Error(ex); MessageDxUtil.ShowError(ex.Message); }
但有時,我們可能會碰到客戶數據不一樣的地方。如年齡可能輸入了“10”,也可能輸入“10歲”這樣的,常規的導入,一般是以第一個出現的數值而定,如果是字符串,那么后面的數值可能導入就不能正常顯示了。例如,如果是下面的Excel,那么數據Marks列就會以第一行數據為准,后面的那些 “Fail” 字符,將不可識別,在DataTable中的值變為NULL值了。
為了有效錄入非強類型的表格數據,我們可以就不能使用常規的操作代碼,Aspose.Cell的控件提供了一個API,名為ExportDataTableAsString的函數,這個函數是把所有內容轉換為字符串集合類型,這樣所有的內容將被保留。
public System.Data.DataTable ExportDataTableAsString ( Int32 firstRow, Int32 firstColumn, Int32 totalRows, Int32 totalColumns, Boolean exportColumnName ) |
Name | Description |
---|---|
firstRow | The row number of the first cell to export out. |
firstColumn | The column number of the first cell to export out. |
totalRows | Number of rows to be imported. |
totalColumns | Number of columns to be imported. |
exportColumnName | Indicates whether the data in the first row are exported to the column name of the DataTable |
使用Aspose.Cell這個API導入的數據代碼如下所示。
bool exportColumnName = true;
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(); workbook.Open(filepath); Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0]; datatable = worksheet.Cells.ExportDataTableAsString(iFirstRow, iFirstCol, rowNum + 1, colNum + 1, exportColumnName);
使用該函數導入的數據,因為全部都以字符串格式進行導入,就不會出現,有些解析不了的問題了。在Winform中顯示出來的結果顯示,正常。