How can show Excel Sheet Name in dropdownlist using C# - c#

I want to show an excel sheet name in a dropdown list using c#. But using my code, I am able to show excel sheet name but excel sheet name comes with '' and $.
Coming Output is like: Sheet1$, Sheet2$
sheetNameddl.Items.Clear();
sheetNameddl.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetNameddl.DataTextField = "TABLE_NAME";
sheetNameddl.DataValueField = "TABLE_NAME";
sheetNameddl.DataBind();
sheetNameddl.Items.Insert(0, new ListItem("--Select Sheet--", ""));
But the wanted output is like sheet1, sheet2.

GetOleDbSchemaTable returns a DataTable. You can enumerate it and change the names (might need to do before you bind):
sheetNameddl.Items.Clear();
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach(DataRow ro in dt.Rows)
ro["TABLE_NAME"] = ro["TABLE_NAME"].ToString().TrimEnd('$');
sheetNameddl.DataSource = dt;
sheetNameddl.DataTextField = "TABLE_NAME";
sheetNameddl.DataValueField = "TABLE_NAME";
sheetNameddl.DataBind();
sheetNameddl.Items.Insert(0, new ListItem("--Select Sheet--", ""));

Related

C# deleting rows in datatable getting error?

I'm using closedxml to read from excelsheets and isert the data to datatable and I'm searching into the datatable at rows where my columnname = "data" and I need to delete all rows from the datatable and I add the new data that came from the search to the datatable again
that's my code
using (var wb = new XLWorkbook(QC_DataEntry, XLEventTracking.Disabled))
{
var ws = wb.Worksheet(1);
DataTable dataTable = new DataTable();
dataTable = ws.RangeUsed().AsTable().AsNativeDataTable();
DataRow[] result = dataTable.Select("Application= '" + Application_Name + "' ");
dataTable.Rows.Clear();
foreach (DataRow row in result)
{
dataTable.Rows.Add(row[0], row[1], row[2]).BeginEdit();
}
}
But I get Error
System.Data.RowNotInTableException: 'This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row
so how to solve this one or if there another method to search at excelsheet with column name and get only the data i need it will be cool
Thanks

How to keep two digits of double digit string in same Excel cell after data table import in C#

I have some C# code automatically generating a datatable and importing it to an excel doc to be emailed to an entered email address via a CSHTML form. One of the columns is an ID column. Although the IDs are integers starting from 1, through the CSHTML form they are coming in as string form elements.
I used the following code for the datatable and excel import.
DataSet ds = new DataSet("Builder_Report");
DataTable dt = new DataTable("Requested_Data");
DataColumn column;
DataRow row;
var rows_ID = Request.Form.Get("ID");
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Review ID";
column.AutoIncrement = false;
column.Caption = "Review ID";
column.ReadOnly = false;
column.Unique = false;
dt.Columns.Add(column);
........................
foreach (var ID in rows_ID)
{
row = dt.NewRow();
row["Review ID"] = ID;
............
dt.Rows.Add(row);
}
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook requested_report = application.Workbooks.Create();
//Creating a Sheet
IWorksheet sheet = requested_report.Worksheets.Create("Requested Details");
sheet.ImportDataTable(dt, true, 1, 1);
sheet.UsedRange.WrapText = true;
For some reason, for every double digit ID number, the two digits get separated into two different rows, e.g., for ID number 10, "1" appears in one row under the ID Column and 0 appears in the row below it. I'm not sure why that particular string is getting split. This is the only code I have that affects that particular ID column.
What is the data type of rows_ID if you step through this in the debugger? From your code, it looks like you are expecting it to be an array of strings, but I'm betting it's coming through as just a plain old string. Your foreach loop is then looping over each character in the string.
If you are expecting it to be an array, you should name the form field ID[] and change this:
var rows_ID = Request.Form.Get("ID");
to
var rows_ID = Request.Form.Get("ID[]");

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! :)

How do I search data in from datatable based on user input

I have created one datatable:
DataTable dt=new DataTable();
dt.Columns.Add("Country", typeof(string))
dt.Columns.Add("place", typeof(string))
dt.Columns.Add("Price", typeof(string))
dt.Columns.Add("Desc", typeof(string))
and I have inserted some data in this datatable:
DataRow dtrow = dt.NewRow(); // Create New Row
dtrow["Country"] = "India"; //Bind Data to Columns
dtrow["place"] = "wizag";
dtrow["Price"] = "7520";
dtrow["Desc"] = "Anywhere";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
dtrow["Country"] = "India"; //Bind Data to Columns
dtrow["place"] = "Goa";
dtrow["price"] = "4500";
dtrow["Desc"] = "Anything";
dt.Rows.Add(dtrow);
I have bind this datatable with my grid view. I have also added one textbox and one search button in mmy aspx page. My requirement is that I want to search data based on user input e.g like 4500 or wizag, and if country name is the same I want to show it in one row
How can I do this?
I would use a DataView in this case
DataView dv = new DataView(dt);
dv.RowFilter = "price = 4500 AND Country = 'India'";
GridView.DataSource = dv.ToTable();
GridView.DataBind();

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();

Categories

Resources