如何使用Linq To Excel将数据导入GridView

时间:2015-09-08 11:45:36

标签: c# asp.net excel linq linq-to-excel

我想从gridview将数据导入Excel。我已经使用System.Data.OleDb作为

if (ExlSheet.HasFile)
        {
            string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
            string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
            string fileLocation = Server.MapPath("~/App_Data/" + fileName);
            ExlSheet.SaveAs(fileLocation);
            if (fileExtension == ".xls")
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                  fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                  fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }
            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;
            OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
            DataTable dtExcelRecords = new DataTable();
            con.Open();
            DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
            cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
            dAdapter.SelectCommand = cmd;
            dAdapter.Fill(dtExcelRecords);
            gv.DataSource = dtExcelRecords;
            gv.DataBind(); 
        }

如何使用LinqToExcel

实现相同目标

1 个答案:

答案 0 :(得分:1)

试试这个

 if (ExlSheet.HasFile)
        {
            string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
            string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
            string fileLocation = Server.MapPath("~/App_Data/" + fileName);
            ExlSheet.SaveAs(fileLocation);
            ExcelQueryFactory excelFile = new ExcelQueryFactory(fileLocation);

            var data = from a in excelFile.Worksheet("Sheet1") select a;


            var columnNames = excelFile.GetColumnNames("Sheet1");
            DataTable dtExcelRecords = new DataTable();
            foreach (var columnName in columnNames)
            {
                dtExcelRecords.Columns.Add(columnName);
            }
            foreach (var row in data)
            {
                DataRow dr = dtExcelRecords.NewRow();
                foreach (var columnName in columnNames)
                {
                    dr[columnName] = row[columnName];
                }
                dtExcelRecords.Rows.Add(dr);
            }
            gv.DataSource = dtExcelRecords;
            gv.DataBind();
        }