gpt4 book ai didi

c# - 如何使用 C# 获取上传的 excel 文件的工作表名称?

转载 作者:太空狗 更新时间:2023-10-30 00:53:14 25 4
gpt4 key购买 nike

我想使用C# 代码获取上传的excel 文件的工作表名称。该文件可能是 .xls.xlsx 格式。我使用的代码如下:

protected void btnGenerateCSV_Click(object sender, EventArgs e)
{
string sourceFile = ExcelFileUpload.PostedFile.FileName;
string worksheetName = ?? //(How to get the first sheetname of the uploaded file)
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";

if (sourceFile.Contains(".xlsx"))
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";

try
{
conn = new OleDbConnection(strConn);
conn.Open();

cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);

da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
}
catch (Exception exp)
{
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
}
}
  • (如何获取上传文件的第一个sheetname)string worksheetName = ??

最佳答案

我用它从 .xlsx 文件中获取工作表名称,然后遍历所有名称以一张一张地读取工作表。

OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0 xml;HDR=YES;'");
connection.Open();
DataTable Sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

foreach(DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + sht + "]", connection);
}

关于c# - 如何使用 C# 获取上传的 excel 文件的工作表名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17358801/

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