刚做过的,以下生成Excel文件的方法是从项目中复制过来的,如果楼主有疑问,请联系我。 ///
/// 导出Excel表
/// DataTable转化为stream流
/// 直接将NPOI对象写入stream流中
///
/// DataTable数据源
///
public static Stream RenderDataTableToExcel(DataTable sourceTable)
{
var workbook = new HSSFWorkbook();
var ms = new MemoryStream();
var sheet = workbook.CreateSheet();
var headerRow = sheet.CreateRow(0); // handling header.
foreach (DataColumn column in sourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); // handling value.
var rowIndex = 1; foreach (DataRow row in sourceTable.Rows)
{
var dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in sourceTable.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} rowIndex++;
} workbook.Write(ms);
ms.Flush();
ms.Position = 0;
return ms;
}
}
Interop.Microsoft.Office.Interop.Excel.dll Interop.Excel.dll用以上两个类库提供的方法 导到Exce文件当中用PrintDocument 对象打印