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;
}
}
Ok so I got this code off of Microsoft.
theDataAdapter.Fill(DS, "ExcelInfo");
This is the line that gave me the error.
Basically this code is supposed to use a dialog box to open the file and display it on the form. Whenever I opened an Excel file, it would give me this error. I even tried creating a blank excel file and it still gave me this.
Modified your code. added OleDbCommand to do the query selection. just try.
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();
I have seen this error before and it might not have anything to do with your code. The code below works fine, but if you are getting your source that has blocked the file, make sure you right-click the file and go to properties and check unblock. This could be if you are downloading the file from some source etc. A good test is to just open the exported excel file and save it and try again. Or copy the contents into a new excel file.
Again the code below works fine, but when I tried to import without unblocking or going into the file and saving it I was getting the same error. The error message is deceiving.
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];
}
}
Related
Recently my mentor asked me to write a program,manipulating the dbf file in C#.I'm using Odbc & OleDb and now I can read the dbf to datagridview with a dataset.
My question is : how can I input some data in datagridview after reading from the local dbf file and update my input to the local dbf file?
I am new to this, not familiar with relevent APIs so example codes would be a great help.
Here is my code to read the dbf file to datagridvie
string filePath = #"C:\Users\csj\Desktop\db\ZMT.dbf";
FileInfo fi = new FileInfo(filePath);
string mulu = fi.DirectoryName;
string filename = fi.Name;
OleDbConnection conn = new OleDbConnection();
string table = filePath;
string connStr = #"Provider=VFPOLEDB.1;Data Source=" + mulu + ";Collating Sequence=MACHINE";
conn.ConnectionString = connStr;
conn.Open();
string sql = #"select * from " + filename;
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet dt = new DataSet();
da.Fill(dt);
conn.Close(); conn.Dispose();
dataGridView1.DataSource = dt.Tables[0].DefaultView;
Any help?
You should create a OleDbCommandBuilder after you created your OleDbDataAdapter
var builder = new OleDbCommandBuilder(da);
The builder creates Update, Insert and Delete commands for the OleDbDataAdapter.
Then after you made changes in the grid you simply call
da.Update(dt);
That's how it should work ... but I didn't try this for dbfs ...
I want to import data from Excel to database using asp.net. I'm using VS-2012 to do this.
This is my code for the click event. But when I upload the file and click on the button the page shows "Page not found" error.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DbDataReader dr = cmd.ExecuteReader();
string con_str = "Gems1ConnectionString1";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName = "tbl_energy_report";
bulkInsert.WriteToServer(dr);
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
Label1.ForeColor = Color.Green;
Label1.Text = "Succefully Imported the File";
}
else
{
Label1.ForeColor = Color.Red;
Label1.Text = "Please Select A File";
}
}
Please help.
on the first line try to assign the full path manually without using fileupload and with local path like:
string path = #"C:\fileName.xls";
and see if it works!
I'm trying to write a class that will read information from an excel file, but for some reason, it will only run exception-free if the file in question is open in excel. Otherwise, the class throws an OleDbException. The code is as follows:
String filename = #"C:\Users\me\Documents\File.xls";
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [Sheet1$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
int counter = 0;
foreach (DataRow row in dt.Rows)
{
String dataA= row["DataA"].ToString();
String dataB= row["DataB"].ToString();
Console.WriteLine(DataA+ " = " + dataB);
counter++;
if(counter>=40)
break;
}
The error is thrown on conn.Open(), and only occurs when I don't have File.xls open in excel at the same time. Can someone help me fix this? I am not well versed enough with OLEDB to figure out why this is happening. Thanks!
I have been attempting to query an excel file from C# using an OLEDB connection. There are no runtime errors when the program runs, but it returns no results. I have tried it with different excel files but have gotten a similar result.
edit: The excel file is located in the project directory. If I remove the excel file from the current location the program will get a file not found exception.
private void btnRun_Click(object sender, EventArgs e)
{
string strFileName = "playerData.xls";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFileName + ";Extended Properties=" + "\"Excel 8.0;HDR=YES\"";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dgsResults.DataSource = ds;
conn.Close();
}
Does anyone know why this returns no results?
Thanks,
You are using strFileName in the connStr yet you have not provided the path with it.
Should be along the lines of:
string strFileName = #"c:\excel location\playerData.xls";
Apparently the specific data table has to be referenced in the data binding process. Adding the following line after the fill() method has solved the issue.
da.Fill(ds);
dgsResults.DataSource = ds.Tables[0]; //this is the line to be added
I am trying to find the best way of selecting an excel spreadsheet (xls and xlsx) using a fileupload control and then parsing it with filestream object and then populating a dataset.
This is my code so far which does the job but how it differs is I am saving the excel spreadsheet to a folder in my solution then querying the data using Microsoft ACE OLEDB connection.
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
//Path.GetExtension(ctrlFileUpload.PostedFile.ContentType);
string fileLocation =
Server.MapPath("~/App_Data/" + fileName);
ctrlFileUpload.SaveAs(fileLocation);
// Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
}
// Create OleDb Connection and OleD Command
using (OleDbConnection con = new OleDbConnection(connectingString))
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
//DataTable dtExcelRecords = new DataTable();
DataSet ds = new DataSet();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "Select * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
//dAdapter.Fill(dtExcelRecords);
dAdapter.Fill(ds);
//GridView1.DataSource = dtExcelRecords;
//GridView1.DataBind();
}
catch (Exception ex)
{
}
}
}
}
So to summarise I want to read the data in a spreadsheet and then bind it to a dataset but without saving the file to a physical path.
Is there a cleaner way of writing this code that I am missing. Thanks!!
I think it not possible to get data without save file to your server
If you can't save uploded file how can you give Data Source to your oleDbConnection string ??
you can delete file after finish this execution if you don't want to keep the file.
you can also refer this way https://stackoverflow.com/a/12420416/284240