gpt4 book ai didi

c# - 如何将Excel工作表中的数据导入到C#中的数据表中?

转载 作者:行者123 更新时间:2023-12-04 18:06:45 25 4
gpt4 key购买 nike

我在 C# 中使用 Asp.net。我需要将数据从 Excel 工作表导入到 DataTable。该工作表有 100,000 条记录,有四列:名字、姓氏、电子邮件、电话号码。

我该怎么做?

最佳答案

使用以下代码:

public static DataTable exceldata(string filePath)
{
DataTable dtexcel = new DataTable();
bool hasHeaders = false;
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//Looping Total Sheet of Xl File
/*foreach (DataRow schemaRow in schemaTable.Rows)
{
}*/
//Looping a first Sheet of Xl File
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
string query = "SELECT * FROM [" + sheet3 + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);
}

conn.Close();
return dtexcel;

}

来源:http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable

您也可以引用以下问题:Importing Excel into a DataTable Quickly如果您希望更快地导入。

关于c# - 如何将Excel工作表中的数据导入到C#中的数据表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24857876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com