Uderc programming article aggregator sites

How do I fill an Excel spreadsheet with the contents of a DataTable? (C#, OleDb)

Advertisement
The following fills a DataTable with the contents of an Excel spreadsheet.
    oledbCmd.CommandText = "SELECT * FROM [" + stSheetName + "$]";
    DataTable dtDataTable = new DataTable();
    using (OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(oledbCmd))
    oledbAdapter.Fill(dtDataTable);
How do I fill an Excel spreadsheet with the contents of a DataTable?
bhs67
Advertisement
The best answer: You can try this Excel library, it can help u to
export datatable to excel to Database.
After add the reference to your project ,add the following code:
private void button1_Click(object sender, EventArgs e)
//connect database
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString @"Provider=""Microsoft.Jet.OLEDB.4.0"";Data Source=""demo.mdb"";User Id=;Password="
OleDbCommand command = new OleDbCommand();
command.CommandText = "select * from parts";
DataSet dataSet = new System.Data.DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command.CommandText,connection);
dataAdapter.Fill(dataSet);
DataTable t = dataSet.Tables[0];
//export datatable to excel
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
sheet.InsertDataTable(t, true, 1, 1);
book.SaveToFile("insertTableToExcel.xls");
System.Diagnostics.Process.Start("insertTableToExcel.xls");
http://www.e-iceblue.com/Tutorials/Spire.XLS/Spire.XLS-Program-Guide/Data-Export-/Import-Export-Datatable-to-Excel-from-Database.html