C# OLEDBE异常未处理;超出系统资源
好的,我从微软那里得到了这个代码C# OLEDBE异常未处理;超出系统资源,c#,excel,datagridview,oledbexception,C#,Excel,Datagridview,Oledbexception,好的,我从微软那里得到了这个代码 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:\
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;
}
}
这是给我错误的那一行
基本上,这段代码应该使用一个对话框来打开文件并在表单上显示它。每当我打开Excel文件时,它都会给我这个错误。我甚至尝试创建一个空白的excel文件,但它仍然给了我这个信息。修改了您的代码。添加了OleDbCommand以执行查询选择。试试看
theDataAdapter.Fill(DS, "ExcelInfo");
我以前见过这个错误,它可能与您的代码无关。下面的代码工作正常,但是如果您获取的源代码阻止了该文件,请确保右键单击该文件,然后转到“属性”并选中“取消阻止”。这可能是因为您正在从某些源下载文件等。一个好的测试是只打开导出的excel文件并保存它,然后重试。或者将内容复制到新的excel文件中 同样,下面的代码工作正常,但当我尝试导入而不取消阻止或进入文件并保存它时,我得到了相同的错误。错误信息具有欺骗性
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();
你检查过你的连接了吗?配置是否正确?如何检查连接?我在上面的代码中更新了连接字符串。。请使用该连接字符串进行检查…:)<代码>数据适配器.Fill(DS,“ExcelInfo”)代码>仍给出此错误。我刚刚复制了这段编辑过的代码:(您好……我使用了“Microsoft.Jet.OLEDB.4.0”作为提供程序和“Extended Properties=Excel 8.0”,它对我来说非常适合……请使用新的连接字符串重试……:)我面临类似的问题,只想分享一个观察结果。打开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];
}
}