【代码沉淀】 - EPPlus - 操作xlsx表格文件

EPPlus - Create advanced Excel spreadsheets on the server.
web: http://epplus.codeplex.com/
nuget: Install-Package EPPlus

操作xlsx表格文件,不需要安装office支持Excel


更多相关项目,请访问代码沉淀目录

重要提示:请注意项目的版本,以官方最新版本为准。


 

下方演示将DataTable保存为xlsx文件

using (ExcelPackage pck = new ExcelPackage(newFile))
{
  ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
  ws.Cells["A1"].LoadFromDataTable(dataTable, true);
  pck.Save();
}

下方演示将xlsx文件读取为DataTable

public static DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
    using (var pck = new OfficeOpenXml.ExcelPackage())
    {
        using (var stream = File.OpenRead(path))
        {
            pck.Load(stream);
        }
        var ws = pck.Workbook.Worksheets.First();  
        DataTable tbl = new DataTable();
        foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
        {
            tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
        }
        var startRow = hasHeader ? 2 : 1;
        for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
        {
            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
            DataRow row = tbl.Rows.Add();
            foreach (var cell in wsRow)
            {
                row[cell.Start.Column - 1] = cell.Text;
            }
        }
        return tbl;
    }
}

 

posted @ 2016-05-11 17:26  三台  阅读(1809)  评论(0编辑  收藏  举报