0
public void LoadExcel_Click(object sender, EventArgs e)
{
    OpenFileDialog fileDLG = new OpenFileDialog();
    fileDLG.Title = "Open Excel File";
    fileDLG.Filter = "Excel Files|*.xls;*.xlsx";
    fileDLG.InitialDirectory = @"C:\Users\...\Desktop\";

    if (fileDLG.ShowDialog() == DialogResult.OK)
    {
        string filename = System.IO.Path.GetFileName(fileDLG.FileName);
        string path = System.IO.Path.GetDirectoryName(fileDLG.FileName);
        excelLocationTB.Text = @path + "\\" + filename;
        string ExcelFile = @excelLocationTB.Text;
        if (!File.Exists(ExcelFile))
            MessageBox.Show(String.Format("File {0} does not Exist", ExcelFile));

        OleDbConnection theConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=Excel 12.0;");
        theConnection.Open();
        OleDbDataAdapter theDataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", theConnection);
        DataSet DS = new DataSet();
        theDataAdapter.Fill(DS, "ExcelInfo");
        dataGridView1.DataSource = DS.Tables["ExcelInfo"];
        formatDataGrid();
        MessageBox.Show("Excel File Loaded");
        toolStripProgressBar1.Value += 0;
    }
}

好的,所以我从微软那里得到了这段代码。

theDataAdapter.Fill(DS, "ExcelInfo");

这是给我错误的行。

基本上,这段代码应该使用一个对话框来打开文件并将其显示在表单上。每当我打开一个 Excel 文件时,它都会给我这个错误。我什至尝试创建一个空白的 excel 文件,它仍然给了我这个。

4

2 回答 2

1

修改了你的代码。添加了 OleDbCommand 来进行查询选择。试试看嘛。

OleDbConnection theConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Projects\Demo\Demo.xls;Extended Properties=Excel 8.0;");
        theConnection.Open();
        OleDbCommand theCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", theConnection);
        OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(theCmd);
        DataSet DS = new DataSet();
        theDataAdapter.Fill(DS);
        theConnection.Close();
于 2014-01-14T04:07:06.107 回答
0

我以前见过这个错误,它可能与你的代码没有任何关系。下面的代码可以正常工作,但是如果您获取的源已阻止该文件,请确保您右键单击该文件并转到属性并检查取消阻止。这可能是您从某个来源等下载文件。一个好的测试是打开导出的 excel 文件并保存并重试。或者将内容复制到一个新的 excel 文件中。

下面的代码再次运行良好,但是当我尝试在不取消阻止或进入文件并保存的情况下导入时,我得到了同样的错误。错误信息具有欺骗性。

string excelconString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1""", filePath);
string excelQuery = "select col1 from [Sheet1$]";

DataSet ds = new DataSet();
DataTable dt = new DataTable();

using (var excelConn = new OleDbConnection(excelconString))
{
    excelConn.Open();
    using (var oda = new OleDbDataAdapter(excelQuery, excelConn))
    {
        oda.Fill(ds);
        dt = ds.Tables[0];
    }
}
于 2019-10-10T13:10:09.837 回答