gpt4 book ai didi

c# - 如何在 C# 中加载带密码的 Excel 文件

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:11 25 4
gpt4 key购买 nike

我从事 C# 项目

我使用以下代码在数据集上导入 XLS 或 XLSX 文件。

public static DataSet ImportExcelXLS(string FileName, bool hasHeaders)
{
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
}

DataSet output = new DataSet();

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

DataTable schemaTable = conn.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

foreach (DataRow schemaRow in schemaTable.Rows)
{
string sheet = schemaRow["TABLE_NAME"].ToString();

if (!sheet.EndsWith("_"))
{
try
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;

sheet = sheet.Replace("$", "");
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
catch (Exception ex)
{
throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
}
}
}
}
return output;
}

此代码可以在没有密码的情况下正确加载 Excel 文件。但是当运行加载带有密码的文件时显示错误:

Cannot start your application. The workgroup information file is missing or opened exclusively by another user.

现在如何更改我的代码以加载加密文件?

最佳答案

请:使用这个库:

using Microsoft.Office.Interop.Excel

请提供密码:

WorkbookObject.Password = password;

请更改 ConnString:

string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Password=password;Extended Properties='Excel 8.0;HDR=YES'";

在这里,你的答案是:

 if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Password=password;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Password=password;Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
}

关于c# - 如何在 C# 中加载带密码的 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13645122/

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