代码改变世界

c# ASP.Net 使用开源免费类库操作Excel

2014-08-07 23:15  朱峰(Peter.zhu)  阅读(2098)  评论(0编辑  收藏  举报

 

主要找到以下类库:

  1. MyXls(http://sourceforge.net/projects/myxls/)
  2. Koogra(http://sourceforge.net/projects/koogra/)  
  3. ExcelLibrary(http://code.google.com/p/excellibrary/)
  4. ExcelPackage(http://excelpackage.codeplex.com/)
  5. EPPlus(http://epplus.codeplex.com/)
  6. LinqToExcel(http://code.google.com/p/linqtoexcel/)
  7. NetOffice(http://netoffice.codeplex.com/) 需安装Office Excel

从1-6的类库均不需要安装Office,不使用Office COM组件;而NetOffice需要安装Office,它提供的是与Office COM组件差不多的功能。

 

ASP.NET MVC File Management
http://file.codeplex.com/

 

 

Excel2Object

Excel 与 Object 互相转换

使用的NPOI

https://github.com/tonyqus/npoi

 

  1. EPPlus(http://epplus.codeplex.com/)
protected void UploadButton_Click(Object sender, EventArgs e)
{
    if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".xlsx")
    {
        using (var excel = new ExcelPackage(FileUpload1.PostedFile.InputStream))
        {
            var tbl = new DataTable();
            var ws = excel.Workbook.Worksheets.First();
            var hasHeader = true;  // adjust accordingly
            // add DataColumns to 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));

            // add DataRows to DataTable
            int 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.NewRow();
                foreach (var cell in wsRow)
                    row[cell.Start.Column - 1] = cell.Text;
                tbl.Rows.Add(row);
            }
            var msg = String.Format("DataTable successfully created from excel-file. Colum-count:{0} Row-count:{1}",
                                    tbl.Columns.Count, tbl.Rows.Count);
            UploadStatusLabel.Text = msg;
        }
    }
    else 
    {
        UploadStatusLabel.Text = "You did not specify a file to upload.";
    }
}