从excel文件读取到datatable asp.net

时间:2014-07-20 02:41:43

标签: asp.net datatable

我上传

后从excel文件中读取此代码
 public static DataTable getDataTableFromExcel(string path)
    {
        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();





            bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
            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 (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
            {
              var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
               var row = tbl.NewRow();
              foreach (var cell in wsRow)
               {
                 row[cell.Start.Column - 1] = cell.Text;
               }
             tbl.Rows.Add(row);
              }
            return tbl;
           }

    }

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string filename = Path.GetFileName(FileUpload1.FileName);
            FileUpload1.SaveAs(Server.MapPath("~/Uploader/") + filename);
            err.Text = "Upload status: File uploaded!";
            DataTable dt =  getDataTableFromExcel(Server.MapPath("~/Uploader/") + filename);
            GridView1.DataSource = dt;
            GridView1.DataBind();

            err.Text = dt.Rows[1].ToString();

        }
        catch (Exception ex)
        {
            err.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }

但我无法理解......如果你能给我一点介绍吗? 以及如何阅读特定列 我需要只阅读第一,第三和第五列并非所有......如何做到这一点?

0 个答案:

没有答案