How to capture WorkBook Name in an .xls file? - c#

Example for file below:
I want to capture the "Customers" (highlighted) as a string.
How do I achieve this in ASP.NET/C#?
Thank you.

You may use OleDbConnection.GetOleDbSchemaTable method.
connection.Open();
DataTable schemaTable = connection.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables,
new object[] { null, null, null, "TABLE" });
foreach (DataRow row in schemaTable.Rows )
{
Console.WriteLine(row["TABLE_NAME"]);
}

public static List<string> GetSheetNames(string PathToExcelFile)
{
List<string> SheetNameList = new List<string>();
System.Data.DataTable SchemaTable;
string OleConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + PathToExcelFile + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"";
using (System.Data.OleDb.OleDbConnection OleConnection = new System.Data.OleDb.OleDbConnection(OleConnectionString))
{
OleConnection.Open();
SchemaTable = OleConnection.GetSchema("Tables");
OleConnection.Close();
}
foreach (System.Data.DataRow SchemaRow in SchemaTable.Rows)
{
SheetNameList.Add(SchemaRow["TABLE_NAME"].ToString().TrimEnd('$'));
}
return SheetNameList;
}

Related

Read a single cell from Excel to a string using C# and ASP.NET

I need to read a single cell from an xsl excel file to a string withing the web application i am building. I was previously pulling cell ranges from the file to a table using the following code:
string PullFromExcell(string CellNo)
{
string cell;
string properties = String.Format(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\User\Desktop\file.xls; Extended Properties = 'Excel 8.0;'");
using (OleDbConnection conn = new OleDbConnection(properties))
{
string worksheet = "Sheet";
conn.Open();
DataSet ds = new DataSet();
using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + worksheet + "$" + CellNo + "]", properties))
{
DataTable dt = new DataTable();
cell = dt.ToString();
da.Fill(dt);
ds.Tables.Add(dt);
grdComponent.DataSource = dt;
grdComponent.DataBind();
}
}
return cell;
}
How would i send that to a string? The code that i would use when pulling from a database is similar to this:
Sqlstring = "Select data from variable where name = 'fred' and ssn = 1234";
var cmd0 = new SqlCommand(Sqlstring, Class_Connection.cnn);
string Data = cmd0.ExecuteScalar().ToString();
i'm just not sure if any of that is compatible.
After filling DataTable, you can search the row like this:
foreach (DataRow dr in dt.Rows)
{
if (dr["name"] == "fred" && dr["ssn"] == "1234")
{
cell = dr["data"].ToString();
break;
}
}

C# Cannot access DataTables column via its columnname

I have a DataTable which I save into a CSV file.
If I now read that CSV file and fill the value of it into a new DataTable the first column has a questionmark before it. Like '?Strasse'.
I guess there is a encoding issue, but I don't know how to fix it.
Code that generates CSV:
private static void SaveProgressToCSV(List<DataTable> dts)
{
int count = 0;
_pathToCSVs = new List<string>();
foreach (DataTable dt in dts)
{
count++;
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + #"\save"+ count + ".csv", sb.ToString(), Encoding.UTF8);
_pathToCSVs.Add(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + #"\save" + count + ".csv");
}
}
Code that reads CSV:
private static void ReadCSVIntoDataTable()
{
DataTable = new List<System.Data.DataTable>();
foreach (String pathToSave in _pathToSave)
{
DataTable dt = new System.Data.DataTable();
string pathOnly = Path.GetDirectoryName(pathToSave);
string fileName = Path.GetFileName(pathToSave);
string sql = #"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=Yes;CharacterSet=65001;\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dt);
}
DataTable.Add(dt);
}
}
Like #juharr mentioned in the comments, I tried a CSV parser library.
The one I choose was the GenericParser.
Here the code including the GenericParser that fixed my encoding issue:
private static void ReadCSVIntoDataTable()
{
foreach (String pathToSave in _pathToSave)
{
var adapter = new GenericParsing.GenericParserAdapter(pathToSave, Encoding.UTF8);
adapter.FirstRowHasHeader = true;
DataTable dt = adapter.GetDataTable();
DataTableToExpose.Add(dt);
}
}
Thanks for the help #everyone.

Error when i read excel file by C#

I read excel but dataGridView show data than lines excel file, So I can't write datagridview.Rowcount(). I use the below given code to read the excel file.
Code:
filePath = txtExcelFile.Text;
string[] fileSpit = filePath.Split('.');
if (filePath.Length > 1 && fileSpit[1] == "xls")
{
connString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=No'";
}
else
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=No'";
}
OleDbCommand cmd = new OleDbCommand(#"Select * from [" +comboBox1.SelectedValue.ToString() + "]", ole);
OleDbDataAdapter oledata = new OleDbDataAdapter();
oledata.SelectCommand = cmd;
DataSet ds = new DataSet();
oledata.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
Either strip out the blank lines from the data table before assigning it to the grid:
private DataTable StripEmptyRows(DataTable dt)
{
List<int> rowIndexesToBeDeleted = new List<int>();
int indexCount = 0;
foreach(var row in dt.Rows)
{
var r = (DataRow)row;
int emptyCount = 0;
int itemArrayCount = r.ItemArray.Length;
foreach(var i in r.ItemArray) if(string.IsNullOrWhiteSpace (i.ToString())) emptyCount++;
if(emptyCount == itemArrayCount) rowIndexesToBeDeleted.Add(indexCount);
indexCount++;
}
int count = 0;
foreach(var i in rowIndexesToBeDeleted)
{
dt.Rows.RemoveAt(i-count);
count++;
}
return dt;
}
Or do your own row count ignoring blank rows.

Get DocumentText from Excel

I need to get all document formatted text from an excel spreadsheet.
I need a better solution that this. This achieves my goal but does not scale at all!
StringBuilder strData = new StringBuilder();
var worksheets = ReferenceDocument.Worksheets;
foreach (Excel._Worksheet worksheet in worksheets)
{
foreach (var cell in worksheet.UsedRange.Cast<Excel.Range>())
{
object value = cell.Text;
string strValue = value == null ? null : value.ToString();
if (!String.IsNullOrWhiteSpace(strValue)) strData.AppendLine(strValue);
}
}
EDIT: I've tried calling worksheet.UsedRange.Text to get an array of strings, but unfortunately it returns System.DbNull and not an array.
I couldn't find anything in the Excel object model I could use. I solved issue by using OleDb
StringBuilder strData = new StringBuilder();
ReferenceDocument.SaveCopyAs(strSomeTempFile);
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended properties=\"Excel 8.0;IMEX=1;HDR=NO\"", strSomeTempFile);
var cnn = new OleDbConnection(cnnStr);
try
{
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach(DataRow schemaRow in schemaTable.Rows)
{
string worksheetName = schemaRow["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheetName);
var da = new OleDbDataAdapter(sql, cnn);
var dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
foreach (DataColumn col in dt.Columns)
{
var value = row[col.ColumnName];
if (!(value is System.DBNull)) strData.AppendLine(value.ToString());
}
}
}
catch (Exception e)
{
// handle error
throw;
}
finally
{
cnn.Close();
}
return strData;

Oledb skips the first column of excel file. The first column is empty

The problem is that the first column is empty and it can not be read.
To read the file, I wrote the following code:
MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "'" + filename + "'" + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0\"");
DtSet = new DataSet();
MyConnection.Open();
var dt = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
MyCommand = new OleDbDataAdapter("select * from [$first]", MyConnection);
MyCommand.Fill(DtSet); // filldata
dataExcel.AddRange(fillData(DtSet.Tables["Table"]).Select(info => info.ToList()));
}
List<List<string>> fillData(DataTable DtSet) //reader
{
List<List<string>> data = new List<List<string>>();
foreach (DataRow item in DtSet.Rows)
{
if (item == null) continue;
List<string> gettedData = new List<string>();
int i = 0;
foreach (var columnitem in item.ItemArray)
{
if (i == 0 && columnitem.ToString() == "") ;
else gettedData.Add(columnitem.ToString()); //add data
i++;
}
data.Add(gettedData);
}
return data;
}
This code works but the first column, he does not see. Thank you!

Categories

Resources