用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - asp代码库

数据导出到Excel(DataSet)

2012-10-19 作者: 程序猿style举报

[asp]代码库

static class ExportingCellByCellMethod
{
	public static void ExportToExcel ( DataSet dataSet, string outputPath )
	{
		// Create the Excel Application object
		ApplicationClass excelApp = new ApplicationClass();
		// Create a new Excel Workbook
		Workbook excelWorkbook = excelApp.Workbooks.Add ( Type.Missing );
		int sheetIndex = 0;
		// Copy each DataTable as a new Sheet
		foreach ( System.Data.DataTable dt in dataSet.Tables )
		{
			// Create a new Sheet
			Worksheet excelSheet = ( Worksheet ) excelWorkbook.Sheets.Add (
			                           excelWorkbook.Sheets.get_Item ( ++sheetIndex ),
			                           Type.Missing, 1, XlSheetType.xlWorksheet );
			excelSheet.Name = dt.TableName;
			// Copy the column names (cell-by-cell)
			for ( int col = 0; col < dt.Columns.Count; col++ )
			{
				excelSheet.Cells[1, col + 1] = dt.Columns[col].ColumnName;
			}
			( ( Range ) excelSheet.Rows[1, Type.Missing] ).Font.Bold = true;

			// Copy the values (cell-by-cell)
			for ( int col = 0; col < dt.Columns.Count; col++ )
			{
				for ( int row = 0; row < dt.Rows.Count; row++ )
				{
					excelSheet.Cells[row + 2, col + 1] = dt.Rows[row].ItemArray[col];
				}
			}
		}
		// Save and Close the Workbook
		excelWorkbook.SaveAs ( outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,
		                       Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
		                       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing );
		excelWorkbook.Close ( true, Type.Missing, Type.Missing );
		excelWorkbook = null;
		// Release the Application object
		excelApp.Quit();
		excelApp = null;
		// Collect the unreferenced objects
		GC.Collect();
		GC.WaitForPendingFinalizers();
	}
}


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...