Load Excel sheet issue with C# - c#

I have a problem with reading an Excel document. I have tried for 4 hours now and can't find to fix it. I have the following code for now.
private void button2_Click(object sender, EventArgs e) {
if (!string.IsNullOrEmpty(textBox_sheet.Text)) {
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" + textBox_path.Text +
";Extended Properties=\"Excel 8.0; HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * From [" + textBox_sheet.Text + "$]",
conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
foreach (DataRow row in dt.Rows) {
Console.WriteLine(row[0].ToString());
while (!string.IsNullOrEmpty(row[0].ToString())) {
Console.WriteLine(row[1].ToString());
}
}
dataGridView1.DataSource = dt;
}
}
The problem is when i try to read in the excel sheet. It loads fine on the form but is taking the first value of the excel sheet as the column header name. I don't want this to happen. The excel sheet has the following format.
.
Here is an image of the forms application with the problem.
As you can see it is loading the first row of the excel sheet into the first row on the Datatable.
I don't want that to happen, but I can't figure out how to fix that.

Your connection string to the spreadsheet has been set to view the first row as a header, HDR=Yes;. Simply change it to HDR=No;.

Related

Loading text File into datagrid and long number displayed incorrectly

I'm importing a .txt file into a DataGridView, which works pretty decently right now.
Unfortunately, the one and only important value isn't displayed correctly.
The value (a German tracking number) is: "00340433914967320068"
Please see attached screenshot (column F2) how it is shown in the datagrid.
All other values works like charm.
Even longer ones like: "[x,xx] Gewicht<0>N^[0,00] DHL Paket<101>L^"
screenshot shows problem
Code is:
private void buttonEasy1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
this.labeltxt1.Text = openFileDialog1.SafeFileName;
// .txt einlesen Anfang
string[] lines1 = { "[" + labeltxt1.Text + "]", "Format = Delimited(;)", "ColNameHeader = False "};
System.IO.File.WriteAllLines(#"C:\*\schema.ini", lines1);
string FileName1 = textBox1.Text;
OleDbConnection conn1 = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName1) + ";Extended Properties='text;';");
conn1.Open();
OleDbDataAdapter adapter1 = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName1), conn1);
DataSet ds1 = new DataSet("Temp");
adapter1.Fill(ds1);
conn1.Close();
dataGridView1.DataSource = ds1;
dataGridView1.DataMember = "Table";
// .txt einlesen Ende
Try changing DataGrid column format. For example:
dataGridView1.Columns[1].DefaultCellStyle.Format = "N0";
or
dataGridView1.Columns[1].DefaultCellStyle.Format = "###################";
Further Information with regard to Steve's comment -
I tried those solutions:
How To Change DataType of a DataColumn in a DataTable?
DataTable dtCloned = dt.Clone();
dtCloned.Columns[1].DataType = typeof(String);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
and
adapter.FillSchema(table, SchemaType.Source);
table.Columns[1].DataType = typeof (String);
adapter.Fill(table);
Nothing changed - still displaying 3,40433191496732E+17 instead of 00340433914967320587

Unable to open excell sheet which created by c#

I have created a excel sheet with the help of creating simple excel sheet in c# with strings as input link. It works fine the error when we open the saved excel sheet it shows message box like "excel found unreadable content in "sample.xls". Do you want to recover the contents of this workbook? If you trust the source of this workbook, Click Yes". May I know How it shows like this? My sample code is
protected void Button1_Click(object sender, EventArgs e)
{
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Create a query and fill the data table with the data from the DB
SqlConnection conn= new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd =new SqlCommand ("SELECT Name,EmpCode FROM EmpDetails where EmpCode='"+Neena102+"'",conn);
// dr = conn.query(str);
SqlDataAdapter adr = new SqlDataAdapter();
adr.SelectCommand = cmd;
adr.Fill(dt);
//Add the table to the data set
ds.Tables.Add(dt);
var rows = ds.Tables[0].Rows;
foreach (DataRow row in rows)
{
string name=Convert.ToString(row["Name"]);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook(#"F:\\reports\\"+name+".xls", ds);
System.Diagnostics.Process.Start(#"F:\\reports\\" + name + ".xls");
}
}
Please try the following changes.
Process startExcel = System.Diagnostics.Process.Start(#"F:\reports\" + name + ".xls");
startExcel.WaitForExit();

Import excel header data in a drop down in .net

Hi I am importing a excel or a .csv file using OpenFileDialog in Visual Studio 2005.
I need to show all the headers in a list, which is supposed to be listed on a ComboBox.
e.g If I import a file which has 10 columns in it, my drop down should show me 10 values as
1, 2, 3..........10
Please let me know how to go about it.
CSV is completely different animal than Excel.
I would use the OpenXml library OR use the OleDb driver to read from the excel file.
Look here: Reading excel file using OLEDB Data Provider
You will need to have the ACE driver installed, you may already have it though.
// first read *.xls file into a DataTable; don't wory it is very quick.
public DataTable ReadExcelFile(string strFilePath)
{
string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + "; Extended Properties=\"Excel 8.0; HDR=No; IMEX=1;\"";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
DataTable sdt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Change this part to read 1 row
String str = "SELECT TOP(2) * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
//String str = "SELECT * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
OleDbCommand objCmdSelect = new OleDbCommand(str, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataTable dt = new DataTable();
objAdapter1.Fill(dt);
objConn.Close();
dt.AcceptChanges();
return dt;
}
Now working with DataTable
DataTable dt = ReadExcelFile(#"c:\\x.xlsx");
if (dt != null)
{
System.Windows.Forms.ComboBox cmb = new System.Windows.Forms.ComboBox();
for (int i = 0; i < dt.Columns.Count; i++)
cmb.Items.Insert(i, dt.Columns[i].ColumnName);
}

Searching and displaying data based on ID in Excel on button click in c#

I have Window form and Microsoft Excel as database. I want to implement searching feature. I have 1 textbox 1 datagridview and 1 button and I want whenever I click on button a search should be made in Excel file based on the id provided in textbox and its description should be displayed in gridview.
The code I'm using is not dynamic, it's static. Does that mean it'll only show description of data I provided in code and not in textbox?
My code is
private void srch()
{
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= 'c:\\Product Details.xlsx';Extended Properties='Excel 8.0;HDR=Yes;'";
// double id = Convert.ToDouble(textBox1.Text);
string query = "SELECT * FROM [Sheet1$]";
DataSet excelDataSet = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(query, strConn);
da.Fill(excelDataSet);
dataGridView1.DataSource = excelDataSet.Tables[0];
DataView dv = ((DataTable)dataGridView1.DataSource).DefaultView;
DataView dv_filter = new DataView();
dv_filter.Table = excelDataSet.Tables[0];
dv_filter.RowFilter = "ID = '105'";
dataGridView1.DataSource = dv_filter;
}
do not select all the sheet
use this code instead:
query="select * from [Sheet1$] where id='"+textbox1.text+"';
Datatable dt = new DataTale();
and after selecting the rows use this code:
datagridview.DataSource=dt;
hope it help

OleDbDataAdapter Fill method importing more rows

I'm importing excel into DataTable. The excel file contains 50x7 cells with data.
The problem is that the Fill() method imports 368(?) rows regardless the fact that the data is in the first 50 of them. Any idea what might be the problem ?
I'm using OleDbDataAdapter for the import.
connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
string commandString = "select * from [" + worksheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(commandString, connectionString);
DataTable fileTable = new DataTable();
adapter.Fill(fileTable);
Try this to remove empty cells from the DataTable:
adapter.Fill(fileTable);
fileTable = fileTable.AsEnumerable()
.Where(row => !row.ItemArray.All(f => f is System.DBNull || String.IsNullOrWhiteSpace(f.ToString())))
.CopyToDataTable();
Note that it also removes empty rows inside the sheet.

Categories

Resources