c# - 在 C# 中从 XLSX 中读取数据

标签 c# excel ado.net xlsx

我是 c# 的新手,正在尝试使用以下代码在 c# 中读取 XLSX 文件:

string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=c:\\Temp\\source.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

//code to read the content of format file 
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();

DataTable dt = new DataTable();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Tabelle1$]", con);

myCommand.Fill(dt);
Console.Write(dt.Rows.Count);

我从输出中得到了正确的计数,但我还有 2 个问题:

1.如何做一个select where语句(如何访问行)?

 select * from [Tabelle1$] where A = '123' (A being an existing Excel row)

会抛出错误参数...

2.谁能给我提供教程链接或简短示例如何访问数据?

最佳答案

请引用以下示例代码:

private DataTable LoadXLS(string strFile, String sheetName, String column, String value)
{
    DataTable dtXLS = new DataTable(sheetName);

    try
    {
       string strConnectionString = "";

       if(strFile.Trim().EndsWith(".xlsx")) {

           strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);

       } else if(strFile.Trim().EndsWith(".xls")) {

           strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);

       }

       OleDbConnection SQLConn = new OleDbConnection(strConnectionString);

       SQLConn.Open();

       OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();

       string sql = "SELECT * FROM [" + sheetName + "$] WHERE " + column + " = " + value;

       OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);

       SQLAdapter.SelectCommand = selectCMD;

       SQLAdapter.Fill(dtXLS);

       SQLConn.Close();
    }

    catch (Exception e)
    {
       Console.WriteLine(e.ToString());
    }

    return dtXLS;

}

关于c# - 在 C# 中从 XLSX 中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5886089/

相关文章:

c# - 在继承类上多次定义接口(interface)

c# - 在 Sound forge 中编写脚本

vba - 如何覆盖 scripting.dictionary 中键的值?

c# - 如何刷新绑定(bind)到已更新的 Access 数据库表的 DataGridView?

c# - 使用 OUT 参数调用 MySQL 过程

c# - `There is already an open DataReader` 迭代查询结果时出错

c# - 在 SQL 查询中包含文本框值

c# - 如果用户单击 "X"按钮,则从子窗体关闭父窗体

python - 如何将列表值分配给excel文件中的列?

excel - 在没有数据透视表的情况下根据每日数据计算月平均值