如何使用Linq to Excel导入数据到GridView
本文关键字:数据 GridView 导入 Excel 何使用 Linq to | 更新日期: 2023-09-27 18:11:37
我想从Excel
导入数据到gridview
。我用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
实现相同的
试试这个
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();
}