I'm creating a program to export Excel sheets, and I want to use a list to read in the headers (List<String> lFields) but for some reason it does not work, the DateTime works though.
using (Workbook workbook = new Workbook())
{
Worksheet sht = workbook.Worksheets[0];
try
{
rowcount = 0;
//top headers
sht.Cells[rowcount, 1].Value = DBName;
int cols = lFields.Count() + 3;
sht.Cells[rowcount, cols].Value = Convert.ToString(DateTime.Now);
rowcount++;
//headers
for (int i = 0; i < lFields.Count(); i++)
{
sht.Cells[rowcount, i].Value = lfields[i];
}
//styling
sht.Rows[rowcount].Font.Name = "Calibri";
sht.Rows[rowcount].Font.Size = 10;
sht.Rows[rowcount].Font.Bold = true;
sht.Rows[rowcount].Font.Italic = false;
rowcount++;
sht.FreezeRows(0);
int RowCount = 0;
from Microsfot support :https://support.microsoft.com/en-us/help/306572/how-to-query-and-display-excel-data-by-using-asp-net--ado-net--and-vis
You can query the Excel file as a sql table, and than recover the headers:
// Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("../ExcelData.xls") + ";" +
"Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);
// Open connection with the database.
objConn.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn);
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();
// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");
// Bind data to DataGrid control.
DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
DataGrid1.DataBind();
// Clean up objects.
objConn.Close();
Related
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;
}
}
I am trying to find a faster way to read an XML file that can be opened in Excel 2010. I cannot immediately read the XML file using readxml method because it contains Workbook, style, cell, data and other tags. So my approach was to open it in Excel then get the data on sheet 2 only. The sample file contains 9,000+ rows and takes about 2mins 49secs to store in a datatable. The actual file has 25,000+ rows. This is what I have tried:
private void bulkInsert()
{
var s = new Stopwatch();
s.Start();
try
{
KillExcel();
GCollector();
Excel.Application app = null;
app = new Excel.Application();
Excel.Worksheet sheet = null;
Excel.Workbook book = null;
book = app.Workbooks.Open(#"my directory for the file");
sheet = (Worksheet)book.Sheets[2];
sheet.Select(Type.Missing);
var xlRange = (Excel.Range)sheet.Cells[sheet.Rows.Count, 1];
int lastRow = (int)xlRange.get_End(Excel.XlDirection.xlUp).Row;
int newRow = lastRow + 1;
var cellrow = newRow;
int columns = sheet.UsedRange.Columns.Count;
Excel.Range test = sheet.UsedRange;
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Node_SegmentName");
dt.Columns.Add("Type");
dt.Columns.Add("Sub-Type");
dt.Columns.Add("Description");
dt.Columns.Add("Parameter_DataIdentifier");
dt.Columns.Add("RuntimeValue");
dt.Columns.Add("Category");
dt.Columns.Add("Result");
dt.TableName = "SsmXmlTable";
//slow part
for (i = 0; i < lastRow; i++)
{
DataRow excelRow = dt.NewRow();
for (int j = 0; j < columns; j++)
{
excelRow[j] = test.Cells[i + 2, j + 1].Value2;
}
dt.Rows.Add(excelRow);
}
dataGridView1.DataSource = dt;
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(AppDomain.CurrentDomain.BaseDirectory + String.Format("\\XMLParserOutput{0}.xml", DateTime.Now.ToString("MM-d-yyyy")));
DataSet reportData = new DataSet();
reportData.ReadXml(AppDomain.CurrentDomain.BaseDirectory + String.Format("\\XMLParserOutput{0}.xml", DateTime.Now.ToString("MM-d-yyyy")));
SqlConnection connection = new SqlConnection("Data Source=YOURCOMPUTERNAME\\SQLEXPRESS;Initial Catalog=YOURDATABASE;Integrated Security=True;Connect Timeout=0");
connection.Open();
SqlBulkCopy sbc = new SqlBulkCopy(connection);
sbc.DestinationTableName = "Test";
sbc.WriteToServer(reportData.Tables["SsmXmlTable"]);
connection.Close();
s.Stop();
var duration = s.Elapsed;
MessageBox.Show(duration.ToString() + " bulk insert way");
MessageBox.Show(ds.Tables["SsmXmlTable"].Rows.Count.ToString());//439 rows
}
catch (Exception ex)
{
KillExcel();
GCollector();
MessageBox.Show(ex.ToString() + i.ToString());
}
}
Without the reading from Excel part, the insertion of data using bulk copy only takes a couple of seconds (0.5secs for 449 rows).
For others who are encountering the same issue, what I did was:
save the xml as an xlsx file
use oledb to read the xlsx file
store in dataset using OleDbAdapter (Fill() method)
bulk insert
Here is the code that I used to do this (change the connection string):
Stopwatch s = new Stopwatch();
s.Start();
string sSheetName = null;
string sConnection = null;
System.Data.DataTable sheetData = new System.Data.DataTable();
System.Data.DataTable dtTablesList = default(System.Data.DataTable);
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + #"C:\Users\YOURUSERNAME\Documents\Visual Studio 2012\Projects\TestXmlParser\TestXmlParser\bin\Debug\ConsolidatedSSMFiles.xlsx" + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName))
{
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [TEST$]", oleExcelConnection);
sheetAdapter.Fill(sheetData);
} s.Stop();
var duration = s.Elapsed;
oleExcelConnection.Close();
dataGridView1.DataSource = sheetData;
MessageBox.Show(sheetData.Rows.Count.ToString()+"rows - "+ duration.ToString());
This reads 25000+ rows of excel data to a datable in approx. 1.9 to 2.0 seconds.
I am trying to import a excel spreadsheet into a an array of datatables. Each table will be a sheet from the spreadsheet. Right now I am seeing that each table contains the information from all sheets. I am thinking this part is not working correctly.
dataSet.Clear();
Let me know if you can see what I am doing wrong.
Here is the rest of the code.
public DataTable[] ReadDoc()
{
string filename = #"C:\Documents and Settings\user\Desktop\Test.xlsx";
DataTable dt = null;
string connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";", filename);
OleDbConnection connection = new OleDbConnection(connectionString);
DataSet dataSet = new DataSet();
DataSet finalDataSet = new DataSet();
DataTable[] table = new DataTable[3];
connection.Open();
dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
// Loop through all of the sheets if you want too...
for (int j = 0; j < excelSheets.Length; j++)
{
string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]");
dataSet.Clear();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
dataAdapter.Fill(dataSet);
table[j] = dataSet.Tables[0];
}
return table;
}
Thanks for the help.
The problem here is your dataSet, is declared outsife the for. Each datatable array item is getting the same information. dataSet.Tables[0]; You must declare inside the for. Each iteration store different information.
for (int j = 0; j < excelSheets.Length; j++)
{
DataSet dataSet = new DataSet();
string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]");
.....
}
I am trying to fetch data from excel using below C# code. I am getting the value from two
columns into single variable(str).
I want that value into different variables.So that i can send that value at runtime for two different statements.
How to bring them into two different variable?
string currentSheet = "Sheet1";
excelApp = new Excel.Application();
//Opening/adding Excel file
excelWorkbook = excelApp.Workbooks.Add(workbookPath);
excelSheets = excelWorkbook.Sheets;
excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
//Gives the used cells in the sheet
range = excelWorksheet.UsedRange;
for (rowCnt = 1; rowCnt <= range.Rows.Count; rowCnt++)
{
for (colCnt = 1; colCnt <= range.Rows.Count;colCnt++)
{
str = (string)(range.Cells[rowCnt,colCnt] as Excel.Range).Value2;
System.Console.WriteLine(str);
}
}
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", con);
myCommand.Fill(dt);
con.Close();
for (rowCnt = 1; rowCnt <= range.Rows.Count; rowCnt++)
{
string Charity = (string)(range.Cells[rowCnt, 1] as Excel.Range).Value;
string Country = (string)(range.Cells[rowCnt, 2] as Excel.Range).Value;
System.Console.WriteLine(Charity + " --- " + Country);
}
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);
}