您的位置:首页 > 编程语言 > ASP

利用Aspose.Cell控件导入Excel非强类型的数据

2013-07-27 21:35 507 查看
导入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 )
NameDescription
firstRowThe row number of the first cell to export out.
firstColumnThe column number of the first cell to export out.
totalRowsNumber of rows to be imported.
totalColumnsNumber of columns to be imported.
exportColumnNameIndicates 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中显示出来的结果显示,正常。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐