【发布时间】:2014-01-14 03:50:29
【问题描述】:
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;
}
}
好的,我从 Microsoft 获得了这段代码。
theDataAdapter.Fill(DS, "ExcelInfo");
这是给我错误的那一行。
基本上,这段代码应该使用对话框来打开文件并将其显示在表单上。每当我打开一个 Excel 文件时,它都会给我这个错误。我什至尝试创建一个空白的 excel 文件,它仍然给了我这个。
【问题讨论】:
-
我遇到了类似的问题,只是想分享一个观察。当我打开 excel 文件时,单击启用编辑并再次单击保存。读取相同的文件没有错误。
标签: c# excel datagridview oledbexception