【轉】Aspose.Cells讀取excel文件

 

Aspose是一個很強大的控件,能夠用來操做word,excel,ppt等文件,用這個控件來導入、導出數據很是方便。其中Aspose.Cells就是用來操做Excel的,功能有不少。我所用的是最基本的功能,讀取Excel的數據並導入到Dataset或數據庫中。讀取Excel表格數據的代碼以下:
首先要引入命名空間:using Aspose.Cells;html

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.htmlspa

 

 

簡單封裝:excel

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;
        }
    }
}

調用:code

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

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

相關文章
相關標籤/搜索