0
我有數據表。我需要導入到Excel Template.How這些數據表中的值來實現這一如何導入數據到excel表
我有數據表。我需要導入到Excel Template.How這些數據表中的值來實現這一如何導入數據到excel表
有許多選項
的選項中,我喜歡選擇5性能和簡單性,特別是在服務器端需要時,如果您需要XLSX文件而不是XLS,選項6是很好的,選項7與5和6相比具有陡峭的學習曲線。
試試這個 -
// TO USE:
// 1) include COM reference to Microsoft Excel Object library
// add namespace...
// 2) using Excel = Microsoft.Office.Interop.Excel;
private static void Excel_FromDataTable(DataTable dt)
{
// Create an Excel object and add workbook...
Excel.ApplicationClass excel = new Excel.ApplicationClass();
// true for object template???
Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
// Add column headings...
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
excel.Cells[1, iCol] = c.ColumnName;
}
// for each row of data...
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
}
}
// Global missing reference for objects we are not defining...
object missing = System.Reflection.Missing.Value;
// If wanting to Save the workbook...
workbook.SaveAs("MyExcelWorkBook.xls",
Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
// If wanting to make Excel visible and activate the worksheet...
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
((Excel._Worksheet)worksheet).Activate();
// If wanting excel to shutdown...
((Excel._Application)excel).Quit();
}
永遠記住,谷歌是你的朋友: http://www.codeproject.com/KB/office/ExcelDataTable.aspx http://msmvps.com/blogs/deborahk/archive/2009/07/ 23/write-data-from-a-datatable-to-excel.aspx http://www.dotnetspider.com/resources/29183-Export-DataTable-Excel-using-c-with.aspx – MaQleod 2010-08-30 06:00:48