【转】Aspose.Cells读取excel文件


Aspose是一个很强大的控件,可以用来操作word,excel,ppt等文件,用这个控件来导入、导出数据非常方便。其中Aspose.Cells就是用来操作Excel的,功能有很多。我所用的是最基本的功能,读取Excel的数据并导入到Dataset或数据库中。读取Excel表格数据的代码如下:
首先要引入命名空间:using Aspose.Cells;

Workbook workbook = new Workbook();
workbook.Open("C:\\test.xlsx");
Cells cells = workbook.Worksheets[0].Cells;

for (int i = 0; i < cells.MaxDataRow + 1; i++)
{
for (int j = 0; j < cells.MaxDataColumn + 1; j++)
{
string s = cells[i, j].StringValue.Trim();
//一行行的读取数据,插入数据库的代码也可以在这里写
}
}

  

返回Datatable:

Cells cells = workbook.Worksheets[1].Cells;
System.Data.DataTable dataTable1 = cells.ExportDataTable(1, 0, cells.MaxDataRow,cells.MaxColumn);//noneTitle
System.Data.DataTable dataTable2 = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow+1,cells.MaxColumn,true);//showTitle
//ExportDataTableAsString防止日期类型的字段被读成了数字字符串 例如“4859.321”

  

转自:http://www.cnblogs.com/ricky_li/p/3738005.html

 

 

简单封装:

namespace Utils
{
    public class AsposeExcell
    {
        public static DataTable ExportToDataTableAsString(string excelFilePath,bool showTitle=true)
        {
            Workbook workbook = new Workbook();
            workbook.Open(excelFilePath);
            Cells cells = workbook.Worksheets[0].Cells;

            System.Data.DataTable dataTable2 = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxColumn+1, showTitle);//showTitle
            return dataTable2;
        }
        public static DataTable ExportToDataTableAsString(Stream stream, bool showTitle = true)
        {
            Workbook workbook = new Workbook();
            workbook.Open(stream);
            Cells cells = workbook.Worksheets[0].Cells;

            System.Data.DataTable dataTable2 = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxColumn+1, showTitle);//showTitle
            return dataTable2;
        }
    }
}

调用:

System.Data.DataTable dataTable2 = Utils.AsposeExcell.ExportToDataTableAsString(savePath); 

From:http://www.cnblogs.com/xuejianxiyang/p/5307259.html

 

posted @ 2016-03-22 16:41  Ace001  阅读(15389)  评论(0编辑  收藏  举报