C# DataSet数据导入Excel 修正版- .net FrameWork 4.0以上

 引入  Microsoft.Office.Interop.Excel.dll
格式:标题加了下划线,单元格内容居中
1 using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI; public static void DataSetToExcel(DataTable dataTable, string SaveFile)
{
Microsoft.Office.Interop.Excel.Application excel; Microsoft.Office.Interop.Excel._Workbook workBook; Microsoft.Office.Interop.Excel._Worksheet workSheet; object misValue = System.Reflection.Missing.Value; excel = new Microsoft.Office.Interop.Excel.Application(); workBook = excel.Workbooks.Add(misValue); workSheet = (Microsoft.Office.Interop.Excel._Worksheet)workBook.ActiveSheet; int rowIndex = ; int colIndex = ; //取得标题
foreach (DataColumn col in dataTable.Columns)
{
colIndex++; excel.Cells[, colIndex] = col.ColumnName;
Microsoft.Office.Interop.Excel.Range range = workSheet.Range[workSheet.Cells[, colIndex],workSheet.Cells[,colIndex]];
range.Font.Underline = true;
} //取得表格中的数据
foreach (DataRow row in dataTable.Rows)
{
rowIndex++; colIndex = ; foreach (DataColumn col in dataTable.Columns)
{
colIndex++; excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString().Trim(); Microsoft.Office.Interop.Excel.Range range = workSheet.Range[excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]];
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
}
} excel.Visible = false;
excel.DisplayAlerts = false; if (workSheet != null)
{
workBook.SaveAs(SaveFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
} dataTable = null; workBook.Close(true, misValue, misValue); excel.Quit(); releaseObject(workSheet); releaseObject(workBook); releaseObject(excel); } private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch
{
obj = null;
}
finally
{
GC.Collect();
}
}

Call funxction example:

  DataSetToExcel(ds.Tables[], @"D:\ZhaoNick\Desktop\test.xls");

这次需要做一个windowServices,主要的功能就是从local db提取数据存入ftp excel file中,在提取数据成功后存入dataset中,在导入到excel时要给标题加下划线和内容设置居中时,发现报了“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: “object”未包含“get_Range”的定义”这么一段错误,后来才发现是.net版本问题或者说是写法有问题。。不过最后还是解决了这个坑。

上一篇:在美国,一名 Uber 司机能赚多少?


下一篇:SQL生成一柱双色球