最近,应项目的需求,需要实现Excel的导入导出功能,对于Web架构的Excel导入导出功能,比较传统的实现方式是:
1)导入Excel:将Excel文件上传到服务器的某一文件夹下,然后在服务端完成Excel的读取及数据的存储;
2)导出Excel:在服务端生成需要导出的Excel,然后下载到客户端。
其中,文件的上传和下载本文不在详述,以下主要写一些DataTable或DataSet与Excel之间的相互转换。
转换方式多种多样,网上也有很多前辈分享的代码实现,本文也借鉴了前辈的诸多思路及代码,具体方法如下:
1. DCOM方式
使用DCOM方式实现Excel的导入导出功能,首先需要在服务端安装office软件。
具体实现代码如下:
1)数据导出到Excel
public class ExportExcel : IDisposable { private Excel.ApplicationClass excelApp; private Excel.Workbook workBook; private Excel.Worksheet workSheet; private Excel.Range range; public void DataTableToExcel(DataTable sourceTable, string fileName) { excelApp = new Excel.ApplicationClass(); if (excelApp == null) { throw new Exception("打开Excel程序错误!"); } workBook = excelApp.Workbooks.Add(true); workSheet = (Excel.Worksheet)workBook.Worksheets[1]; int rowIndex = 0; //写入列名 ++rowIndex; for (int i = 0; i < sourceTable.Columns.Count; i++) { workSheet.Cells[rowIndex, i + 1] = sourceTable.Columns[i].ColumnName; } range = workSheet.get_Range(workSheet.Cells[rowIndex, 1], workSheet.Cells[rowIndex, sourceTable.Columns.Count]); FontStyle headerStyle = new FontStyle { FontSize = 30, BordersValue = 1, FontBold = true, EntireColumnAutoFit = true }; FontStyleHelper.SetFontStyleForRange(range, headerStyle); //写入数据 ++rowIndex; for (int r = 0; r < sourceTable.Rows.Count; r++) { for (int i = 0; i < sourceTable.Columns.Count; i++) { workSheet.Cells[rowIndex, i + 1] = ExportHelper.ConvertToCellData(sourceTable, r, i); } rowIndex++; } range = workSheet.get_Range(workSheet.Cells[2, 1], workSheet.Cells[sourceTable.Rows.Count + 1, sourceTable.Columns.Count]); FontStyle bodyStyle = new FontStyle { FontSize = 16, BordersValue = 1, FontAlign = Infrastruction.FontAlign.Right, EntireColumnAutoFit = true }; FontStyleHelper.SetFontStyleForRange(range, bodyStyle); //只保存一个sheet页 //workSheet.SaveAs(fileName, Excel.XlFileFormat.xlTemplate, Type.Missing, Type.Missing, Type.Missing, // Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing); //保存整个Excel workBook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing); workBook.Close(false, Type.Missing, Type.Missing); excelApp.Quit(); Dispose(); } public void Dispose() { GC.Collect(); BaseExcel.Dispose(excelApp, workSheet, workBook, range); } }