Unable to open excell sheet which created by c# - 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();

Related

Cannot read from Excel sheet when worksheet name has spaces

I want to take data into a combobox from an excel sheet. But, the sheetname is not like sheet1$. My excel sheet name is Sac Haddehanesi Kalite Kontrol. When I made my sheet name sheet1, it works. But, the excel file is sent everyone and it is sheet name given by another guy. So, I have to use the original sheet name and cannot read it by the code below:
pintu(textBox8.Text);
try
{
con.Open();
str = "SELECT * FROM [Sac Haddehanesi Kalite Kontrol$]";
com = new OleDbCommand(str, con);
oledbda = new OleDbDataAdapter(com);
ds = new DataSet();
oledbda.Fill(ds, "Sac Haddehanesi Kalite Kontrol$");
con.Close();
dt = ds.Tables["Sac Haddehanesi Kalite Kontrol$"];
int i = 0;
for (i = 0; i <= dt.Rows.Count - 1; i++)
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "[Bobin ID]";
Here's an image of my spreadsheet:
After debugging the issue myself, seems there's a problem with reading the sheet name when it has special characters.
Try reading from the sheet according to its index rather than its name.
The following code reads all sheet names into a temporary DataTable, gets the 1st sheet name and uses it in the rest of the code:
con.Open();
// Read all sheet names into a temporary data table
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Get the FIRST sheet name
string sheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
// Now use this name to select
str = "SELECT * FROM [" + sheetName +"]";
com = new OleDbCommand(str, con);
oledbda = new OleDbDataAdapter(com);
ds = new DataSet();
oledbda.Fill(ds, sheetName);
con.Close();
dt = ds.Tables[sheetName];
I found when I was doing VBA for Excel Macro, every sheet actually has 2 names. Name (Name). There is a name for the title (that you showed) when you open with Excel, but also another name to reference in VBA or other code.
See below in the Excel Sheet Properties:
In Excel, the sheet title is "Can Have Space". This is what you see in the tab for the sheet when you open an Excel file.
In code, the sheet alias/title is actually "CannotHaveSpace". This is what you use to reference this sheet in any code instance. This name cannot contain spaces.
I hope these helped someone out there with the same issues! :)

Load Excel sheet issue with 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;.

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

How to change a DataGridViewTextBoxColumn to a DataGridViewLinkColumn?

I have created a DataGridView and filled it with data from an MS Access database. One of the columns in the database is a hyperlink data type. Instead of it being a DataGridViewLinkColumn in my dataGridView2, it is a DataGridViewTextBoxColumn. Because of this it is displayed as a string and is unusable as a hyperlink. I need to know how to change the type of the column. I've been working on this for a while now and have yet to make any real progress.
This code is in my Form1_Load():
dataGridView2.DataSource = bindingSource2;
GetData2("SELECT ProdName, ProdDesc, PIN, EqVal, AsOf, IssDate, Vendor, Salesperson, OwnerName, InsuredName, Hyperlink FROM ProdInterim WHERE ProdInterim.OwnerID = " + id + "");
The Hyperlink column is the one in question here.
Here is the GetData2():
private void GetData2(string selectCommand)
{
try
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = U:/Syndicate II/Syndicate II.accdb;Persist Security Info = False";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand, connectionString);
OleDbCommandBuilder builder = new OleDbCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource2.DataSource = table;
dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}

Categories

Resources