private void button1_Click(object sender, EventArgs e)
{
DataTable dt = ReadExcel(@"d:\db.xls");
DTtoExcel(dt, @"d:\db2.xls");
return;
}
/// <summary>
///
/// </summary>
/// <param name="sExcelFile"></param>
/// <returns></returns>
public System.Data.DataTable ReadExcel(string sExcelFile)
{
string sConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + sExcelFile + ";Extended Properties=Excel 8.0";
OleDbConnection connection = new OleDbConnection(sConnectionString);
OleDbDataAdapter adp = new OleDbDataAdapter("SELECT * FROM testTable", connection);
DataSet ds = new DataSet();
adp.Fill(ds, "Book1");
return ds.Tables[0];
}
private void DTtoExcel(System.Data.DataTable dt, String fname)
{
Excel.Application excel = new Excel.Application();
int rowIndex = 1;
int colIndex = 0;
Excel.Workbook xbook = excel.Workbooks.Add(true);
foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
xbook.SaveAs(fname, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xbook = null;
excel.Quit();
excel = null;
}