How can i read from excel file - c#

Please can you help me with my actually script. I have done select from excel file but now i dont know how can i added value to my lists. I get data from more files together not only from one.
Here is my actually scripts:
Base button initiate event for read.
private void next_Click(object sender, EventArgs e)
{
for (int i = 0; i < UniqueValue.traceToFile.Count; i++)
{
ReadFromExcel read = new ReadFromExcel();
read.ReadData(UniqueValue.traceToFile[i]);
}
}
After next step is this:
class ReadFromExcel : Config
{
public void ReadData(string fullpath)
{
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string cell = "C7";
string name = "List1";
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}
OleDbConnection con = new OleDbConnection(_ConnectionString);
string strCmd = "SELECT * FROM [" + name + "$" + cell + "]";
OleDbCommand cmd = new OleDbCommand(strCmd, con);
try
{
con.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
}
}
Now I need that this result to be written to my list. i reading only one cells from every files.
List for result is
public static List<int> money = new List<int>();
I really thanks for all answers which can help me.

I think below code will help you.
In this example dt, dt2 and dt3 will consider return from your function ReadData function which have datatable from excel.
public static List<int> money = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name");
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["ID"] = 1;
dt.Rows[dt.Rows.Count - 1]["Name"] = "Test1";
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID", typeof(Int32));
dt2.Columns.Add("Name");
dt2.Rows.Add();
dt2.Rows[dt2.Rows.Count - 1]["ID"] = 2;
dt2.Rows[dt2.Rows.Count - 1]["Name"] = "Test2";
DataTable dt3 = new DataTable();
dt3.Columns.Add("ID", typeof(Int32));
dt3.Columns.Add("Name");
dt3.Rows.Add();
dt3.Rows[dt3.Rows.Count - 1]["ID"] = 3;
dt3.Rows[dt3.Rows.Count - 1]["Name"] = "Test2";
money = (from row in dt.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList();
money.AddRange((from row in dt2.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList());
money.AddRange((from row in dt3.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList());
}

Excel.Application excel;
Excel.Workbook wb;
Excel.Worksheet sh;
DataTable dt=new DataTable();
excel = new Excel.Application();
excel.Visible = true;
wb = excel.Workbooks.Open("File Path");
sh = wb.Sheets.Add();
sh.Name = "Data";
count = 2;
sh.Cells[count, "A"].Value2 = "Column Name 1";
sh.Cells[count, "B"].Value2 = "Column Name 2";
sh.Cells[count, "C"].Value2 = "Column Name 3";
sh.Cells[count, "D"].Value2 = "Column Name 4";
sh.Cells[count, "E"].Value2 = "Column Name 5";
sh.Range["A" + count + "", "E" + count + ""].Font.Size = 12;
sh.Range["A" + count + "", "E" + count + ""].Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
sh.Range["I2"].WrapText = true;
try
{
con.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
sh.Cells[count, "A"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "B"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "C"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "D"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "E"].Value2 = row["Column Name"].ToString();
}
wb.SaveAs("File Path" + "File Nmae" + ".xls");
excel.Workbooks.Close();
excel.Quit();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}

Related

Faster way of storing Excel worksheet to system.data.datatable using C#

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.

reading data from excel file to gridView using asp.net

good day, im reading data from excel file and showing it to gridview. but errors says "The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data."
what i have done:
give full access write to folder for IUSR, NETWORK_SERVICE, NETWORK, EVERYONE, USERS AND ADMIN
thank you in advance.
String filePath = txtBbSource.Text;
String sheetName = txtSheetName.Text;
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'";
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter sda = new OleDbDataAdapter("Select * from [" + sheetName + "$]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
gridBalances.DataSource = dt;
private void FillGrid(string FilePath, string Extension)
{
string conStr = "";
DataTable dt = new DataTable();
/*Add below Commented in Webconfig*/
/* <add name ="Excel03ConString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
<!--connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>-->
<add name ="Excel07ConString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
* */
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, "Yes");
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = connExcel;
try
{
int m = 1;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
//oda.SelectCommand = cmdExcel;
//oda.Fill(dt);
// connExcel.Close();
DataTable myColumns = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SheetName, null });
foreach (DataRow dtRow in myColumns.Rows)
{
if (dtRow["COLUMN_NAME"].ToString() == "Sr No" && dtRow["ORDINAL_POSITION"].ToString() == "1")
{
m++;
}
else if (dtRow["COLUMN_NAME"].ToString() == "Task Name" && dtRow["ORDINAL_POSITION"].ToString() == "2")
{
m++;
}
}
/*column count in excel*/
if (m < 2)
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "Selected file is not in required template format.";
return;
}
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
}
catch (Exception ex)
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "Selected file is not in required template format.";
return;
}
DataTable dt_grd1 = new DataTable();
DataRow drnewrow = null;
//upload_plan = 1;
foreach (DataRow dtRow in dt.Rows)
{
if (dtRow["Sr No"].ToString() == "" && dtRow["Task Name"].ToString() != "")
{
dt_grd1.Columns.Add(new DataColumn("ID", typeof(string)));
dt_grd1.Columns.Add(new DataColumn("TASK_NAME", typeof(string)));
}
try
{
drnewrow = dt_grd1.NewRow();
drnewrow["ID"] = "";
drnewrow["TASK_NAME"] = dtRow["Task Name"].ToString();
dt_grd1.Rows.Add(drnewrow);
}
catch (Exception ex)
{
//lblError.Visible = true;
////lblError.Text = ex.Message;// "Authentication failed. Please try later.";
//lblError.Text = DataInteraction.Constants.EXCEPTION;
}
}
/*Using Linq Find same TASK_NAME present in Excel*/
if (dt_grd1.Rows.Count >= 1)
{
var Taskresult = from c in dt_grd1.AsEnumerable()
group c by new
{
TaskName2 = c.Field<dynamic>("TASK_NAME"),
} into g
where g.Count() > 1
select new
{
g.Key.TaskName2,
// g.Key.Pin,
Noofrec = g.Count()
};
if (Taskresult.ToList().Count > 0)
{
lblErrMsg.Visible = true;
div_err_log.Visible = false;
lblErrMsg.Text = "Task with same Name not allowed.";
return;
}
}
grdTaskDataCat1.DataSource = dt_grd1;
grdTaskDataCat1.DataBind();
/*End 13th Jan'17*/
lblErrMsg.Visible = true;
lblErrMsg.Text = "Please confirm the details uploaded and press save to complete the upload of Bid plan.";
return;
}

Reading of Excel File c#

Hi guys! I encountered a problem is that I have difficulty reading this Excel file into data grid view as shown above. Any help will be greatly appreciated. Thanks.
These were my codes to read Excel file but there's a error that I have difficulty troubleshooting it.
private void btnSearch_Click(object sender, EventArgs e)
{
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
OpenFileDialog filedlgExcel = new OpenFileDialog();
filedlgExcel.Title = "Select file";
filedlgExcel.InitialDirectory = #"c:\";
filedlgExcel.FileName = txtFileName.Text;
filedlgExcel.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
filedlgExcel.FilterIndex = 1;
filedlgExcel.RestoreDirectory = true;
if (filedlgExcel.ShowDialog() == DialogResult.OK)
{
workbook = ExcelObj.Workbooks.Open(filedlgExcel.FileName);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
//Reading Excel file.
//Creating dataTable to read the containt of the Sheet in File.
//Set header name
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
}
dt.AcceptChanges();
//store coumn names to array
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
//populate fields
for (int Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
{
DataRow dr = dt.NewRow();
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
workbook.Close(true, Missing.Value, Missing.Value);
ExcelObj.Quit();
foreach (DataRow dr in dt.Rows)
{
string strEmployee = dr["Employee Name"].ToString();
obj1 = new List<employeeschedule>();
for (int i = 1; i < dt.Columns.Count; i++)
{
string period = dr[i].ToString();
string[] split = period.Split('–');
employeeschedule es = new employeeschedule();
string day = columnNames[i];
if (split[0] == "REST")
{
es.day = day;
es.startTime = "0000";
es.endTime = "0000";
es.restDay = "Yes";
}
if (split[0] == "OFF")
{
es.day = day;
es.startTime = "0000";
es.endTime = "0000";
es.restDay = "Yes";
}
else
{
es.day = day;
es.startTime = split[0];
es.endTime = split[1];
es.restDay = "No";
}
obj1.Add(es);
}
dict.Add(strEmployee, obj1);
dgvEmployeeShift.DataSource = dt;
}
}
}
The error falls on this part:
dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
It states that "Cannot perform runtime binding on a null reference".
I love using Interop when automating Excel but for your requirement why not use OleDb? It is much faster than using Interop?
TRIED AND TESTED
private void btnSearch_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyCon ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
//~~> Replace this with relevant file path
MyCon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Sample.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");
//~~> Replace this with the relevant sheet name
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyCon);
MyCommand.TableMappings.Add("Table", "MyTable");
DtSet = new System.Data.DataSet();
//~~> Fill Dataset
MyCommand.Fill(DtSet);
//~~> Set Source
dataGridView1.DataSource = DtSet.Tables[0];
MyCon.Close();
}
This worked for me ...........
Browses your local folder , picks up the excel ,displays in grid view.
Using oledb is what i suggest
private void OpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
this.textBox_path.Text = openfiledialog1.FileName;
}
}
private void LoadExcel_Click(object sender, EventArgs e)
{
//string pathConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+textBox_path.Text+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string pathConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_path.Text + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
OleDbConnection conn = new OleDbConnection(pathConn);
conn.Open();
OleDbDataAdapter mydataadapter = new OleDbDataAdapter("Select * from ["+textBox_sheet.Text+"$]", conn);
DataTable dt = new DataTable();
mydataadapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}

Empty Excel spreadsheet returning incorrect rowcount

I'm using the code below to read my Excel spreadsheet (Sample.xls, also below).
Sample.xls
[Sheet 1]
Column 0, Row 0 = "Test 1"
Column 0, Row 1 = "Test 2"
Column 0, Row 2 = "Test 3"
[Sheet 2]
All columns/rows are blank and empty
public void importFileButton_Click(object sender, EventArgs e)
{
string sourcefile = "C:\\Sample.xls";
string sqlQuery = null;
if (File.Exists(sourceFile))
{
DataTable fileSheetInfo = null;
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;\"");
connection.Open();
fileSheetInfo = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int fileSheetCount = fileSheetInfo.Rows.Count;
OleDbCommand command = new OleDbCommand();
String[] sheetNames = new String[fileSheetInfo.Rows.Count];
int i = 0;
foreach (DataRow row in fileSheetInfo.Rows)
{
sheetNames[i] = row["TABLE_NAME"].ToString();
sqlQuery1 = "SELECT * FROM [" + sheetNames[i] + "]";
command.CommandText = sqlQuery1;
OleDbDataAdapter adapter1 = new OleDbDataAdapter(sqlQuery, connection);
DataTable sheetData = new DataTable();
adapter1.Fill(sheetData);
int iRow = sheetData.Rows.Count;
MessageBox.Show("Sheet Name: " + sheetNames[i], "Sheet Name", MessageBoxButtons.OK);
MessageBox.Show("Rows: " + iRow.ToString(), "Row Count", MessageBoxButtons.OK);
i++;
}
}
}
Why does the code return a rowcount of 1 or 2 for the blank sheet (Sheet2)? Why isn't the rowcount displaying as 0 for Sheet 2? I have noticed that the rowcount is 1 if I have the file open in Excel; 2 if the file is closed in Excel.
Thanks for the help!

The First Column of the excel file to put in string variable C#?

What i need id to take the first column of an excel file and put that column in a string variable but numbers that will be taken from excel to be separated with blank space.
For Example:
Excel file:
1
3
4
56
76
7
876
23
43
(in column)
and string in C#
string number = "1 3 4 56 76 7 876 23 43"
Any code will help me
I have made the connection with excel file and i have created the dataset/datatable
but now i can not take those numbers as the sample above ?
If you have the data in a datset...you can do something like this....
////TRY THIS!!!
DataSet dsExcelContent = new DataSet();
//Fill from db
//
StringBuilder builder = new StringBuilder();
foreach (DataRow row in dsExcelContent.Tables[0].Rows)
{
builder.Append(row[0].ToString());
builder.Append(" ");
}
Console.WriteLine(builder.ToString());
.....More exact to your code....
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [sheet1$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet dsExcelContent = new DataSet();
DataTable dsExcelContent1 = new DataTable();
objAdapter1.Fill(dsExcelContent);
dataGridView1.DataSource = dsExcelContent1;
objConn.Close();
int test = dsExcelContent.Tables[0].Rows.Count;
StringBuilder builder = new StringBuilder();
foreach (DataRow row in dsExcelContent.Tables[0].Rows)
{
builder.Append(row[0].ToString());
builder.Append(" ");
}
//s has the data you want.....
string s = builder.ToString();
//REST OF YOUR CODE.....
Have a link - Reading Excel Document
Here's what I would do...first open the spreadsheet with this code.
xlApp = New Excel.Application
filePath = "FILENAME"
xlWorkBook = xlApp.Workbooks.Open(filePath)
xlWorkSheet = xlWorkBook.Worksheets(1)
Then read through the column like this
For data As Integer = 0 To 8
Dim obj As Excel.Range = CType(xlWorkSheet.Cells(data, 1), Range)
If obj.Value IsNot Nothing Then
MyArray(data) = obj.Value
Else
Exit Do
End If
Next
Then you should have all your data in MyArray then loop through and create a string with spaces and you should be good. This code is in VB but it should give you a good idea of the commands and structure to use.
private void Form1_Load(object sender, EventArgs e)
{
String sConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=unsorted.xls;Extended Properties=""Excel 12.0;HDR=NO;""";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [sheet1$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet dsExcelContent = new DataSet();
DataTable dsExcelContent1 = new DataTable();
objAdapter1.Fill(dsExcelContent);
dataGridView1.DataSource = dsExcelContent1;
objConn.Close();
int test = dsExcelContent.Tables[0].Rows.Count;
foreach(DataRow row in dsExcelContent.Tables[0].Rows)
{
StringBuilder builder = new StringBuilder();
foreach (DataColumn col in dsExcelContent.Tables[0].Columns)
{
builder.Append(row[col].ToString());
builder.Append(" ");
}
string s = builder.ToString();
this.label1.Text = s;
string[] numbers = s.Split(' ');
ArrayList numberList = new ArrayList();
int i;
foreach (String num in numbers)
{
if (Int32.TryParse(num, out i))
{
numberList.Add(i);
}
else
Console.WriteLine("'{0}' is not a number!", num);
}
this.listBox1.DataSource = numberList;
}
}
}
You just want to loop through the rows in the Dataset now:
var numberStr = EmptyStr;
foreach (DataRow dr in MyDataSet.Tables[0].Rows)
{
numberStr = EmptyStr ? numberStr += dr[0].ToString() : numberStr += " " + dr[0].ToString();
}
Updated Solution
private void Form1_Load(object sender, EventArgs e)
{
String s = String.Empty;
String sConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=unsorted.xls;Extended Properties=""Excel 12.0;HDR=NO;""";
using (OleDbConnection conn = new OleDbConnection(sConnectionString))
{
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow schemaRow in schemaTable.Rows)
{
string sheet = schemaRow["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
// populate string with value from rows
foreach (DataRow dr in MyDataSet.Tables[0].Rows)
{
s = String.Empty ? s += dr[0].ToString() : s += " " + dr[0].ToString();
}
dataGridView1.DataSource = dsExcelContent1;
objConn.Close();
}
this.label1.Text = s;
string[] numbers = s.Split(' ');
ArrayList numberList = new ArrayList();
int i;
foreach (String num in numbers)
{
if (Int32.TryParse(num, out i))
{
numberList.Add(i);
}
else
{
Console.WriteLine("'{0}' is not a number!", num);
}
}
this.listBox1.DataSource = numberList;
}

Categories

Resources