目前仅尝试过微软官方提供的COM组件以及第三方类库NPOI进行EXCEL文件的操作,COM组件明显效率较低,推荐NPOI或者新兴的MiniExcel。
COM组件读取 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 private DataSet GetExcelData (string excelFilePath ){ DataSet dataSet = new DataSet(); Excel.Application app = new Excel.Application(); Sheets sheets; Workbook workbook = null ; object oMissiong = Missing.Value; string cellContent; try { if (app == null ) { return null ; } workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong); sheets = workbook.Worksheets; System.Data.DataTable dt = new System.Data.DataTable(); for (int p = 1 ; p <= sheets.Count; p++) { Worksheet workSheet = (Worksheet)sheets.get_Item(p); for (int j = 1 ; j <= workSheet.UsedRange.Columns.Count; j++) { Range _range = (Range)workSheet.Cells[2 , j]; dt.Columns.Add(_range.Text.ToString().Trim()); } for (int i = 3 ; i <= workSheet.UsedRange.Rows.Count; i++) { DataRow dr = dt.NewRow(); for (int j = 1 ; j <= workSheet.UsedRange.Columns.Count; j++) { Range _range = (Range)workSheet.Cells[i, j]; cellContent = (_range.Value2 == null ) ? "" : _range.Text.ToString().Trim(); dr[j - 1 ] = cellContent; } dt.Rows.Add(dr); } dataSet.Tables.Add(dt); } } finally { ClosePro(app, workbook); } return dataSet; }
读取过程中的资源释放问题 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 [DllImport("User32.dll" , CharSet = CharSet.Auto) ] public static extern int GetWindowThreadProcessId (IntPtr hwnd, out int ID ) ;public void ClosePro (Excel.Application xlApp, Workbook xlsWorkBook ){ if (xlsWorkBook != null ) xlsWorkBook.Close(true , Type.Missing, Type.Missing); xlApp.Quit(); GC.GetGeneration(xlApp); IntPtr t = new IntPtr(xlApp.Hwnd); GetWindowThreadProcessId(t, out int k); System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); p.Kill(); }
COM组件打开显示Excel 1 2 3 4 Excel.Application app = new Excel.Application(); app.Visible = true ; Excel.Workbook Book = app.Workbooks._Open(ExportDir, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
NPOI读取Excel文件
整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet;行:Row;列:Column;单元格Cell。
NPOI是POI的C#版本,NPOI的行和列的index都是从0开始
参考文档:使用NPOI进行Excel数据的导入导出 (https://www.cnblogs.com/springsnow/p/13123912.html#_label1 )
NPOI读写单张表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 using System;using System.Collections.Generic;using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using System.Data;using System.IO;namespace Vol_Changer_ShortCircuit.Operate { class ExcelHelper { public static DataTable ReadFromExcel (string FilePath ) { IWorkbook wk = null ; string extension = Path.GetExtension(FilePath); try { using (FileStream fs = File.OpenRead(FilePath)) { if (extension.Equals(".xls" )) { wk = new HSSFWorkbook(fs); } else { wk = new XSSFWorkbook(fs); } } ISheet sheet = wk.GetSheetAt(0 ); IRow row = sheet.GetRow(4 ); DataTable result = BuildDataTable(row); if (result != null ) { if (sheet.LastRowNum >= 1 ) { for (int i = 5 ; i < sheet.LastRowNum + 1 ; i++) { IRow temp_row = sheet.GetRow(i); if (temp_row == null ) { continue ; } List<object > itemArray = new List<object >(); for (int j = 0 ; j < result.Columns.Count; j++) { itemArray.Add(GetValueType(temp_row.GetCell(j))); } result.Rows.Add(itemArray.ToArray()); } } } return result; } catch (Exception ex) { } } public static int DataTableToExcel (DataTable data, string sheetName, string fileName, bool isColumnWritten = true ) { IWorkbook workbook = null ; using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (fileName.IndexOf(".xlsx" ) > 0 ) { workbook = new XSSFWorkbook(); } else if (fileName.IndexOf(".xls" ) > 0 ) { workbook = new HSSFWorkbook(); } if (workbook == null ) { return -1 ; } try { ISheet sheet = workbook.CreateSheet(sheetName); int count = 0 ; if (isColumnWritten) { IRow row = sheet.CreateRow(0 ); for (int j = 0 ; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1 ; } for (int i = 0 ; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (int j = 0 ; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } count++; } workbook.Write(fs); return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1 ; } } } private static DataTable BuildDataTable (IRow Row ) { DataTable result = null ; if (Row.Cells.Count > 0 ) { result = new DataTable(); for (int i = 0 ; i < Row.LastCellNum; i++) { if (Row.GetCell(i) != null ) { result.Columns.Add(Row.GetCell(i).ToString()); } } } return result; } private static object GetValueType (ICell cell ) { if (cell == null ) return null ; switch (cell.CellType) { case CellType.Blank: return null ; case CellType.Boolean: return cell.BooleanCellValue; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(cell)) { return cell.DateCellValue; } return cell.NumericCellValue; case CellType.String: return cell.StringCellValue; case CellType.Error: return cell.ErrorCellValue; case CellType.Formula: cell.SetCellType(CellType.String); return cell.StringCellValue; default : return "=" + cell.CellFormula; } } } }
多张表处理方案 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 using System;using System.Collections.Generic;using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using System.Data;using System.IO;namespace Vol_Changer_ShortCircuit.Operate { class ExcelHelper { public static DataSet ReadFromExcels (string FilePath ) { DataSet ds = new DataSet(); IWorkbook wk = null ; string extension = Path.GetExtension(FilePath); try { using (FileStream fs = File.OpenRead(FilePath)) { if (extension.Equals(".xls" )) { wk = new HSSFWorkbook(fs); } else { wk = new XSSFWorkbook(fs); } } int SheetCount = wk.NumberOfSheets; if (SheetCount < 1 ) { return ds; } for (int s = 0 ; s < SheetCount; s++) { ISheet sheet = wk.GetSheetAt(s); IRow row = sheet.GetRow(0 ); if (row == null ) { continue ; } DataTable tempDT = BuildDataTable(row); tempDT.TableName = wk.GetSheetName(s); if (tempDT != null ) { if (sheet.LastRowNum >= 1 ) { for (int i = 1 ; i < sheet.LastRowNum + 1 ; i++) { IRow temp_row = sheet.GetRow(i); if (temp_row == null ) { continue ; } List<object > itemArray = new List<object >(); for (int j = 0 ; j < tempDT.Columns.Count; j++) { itemArray.Add(GetValueType(temp_row.GetCell(j))); } tempDT.Rows.Add(itemArray.ToArray()); } } ds.Tables.Add(tempDT); } } return ds; } catch (Exception ex) { return null ; } } public static bool DataTableToExcel (DataSet ds, string fileName, bool isColumnWritten = true ) { if (ds == null || ds.Tables.Count < 1 ) { return false ; } IWorkbook workbook = null ; using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (fileName.IndexOf(".xlsx" ) > 0 ) { workbook = new XSSFWorkbook(); } else if (fileName.IndexOf(".xls" ) > 0 ) { workbook = new HSSFWorkbook(); } if (workbook == null ) { return false ; } try { foreach (DataTable dt in ds.Tables) { ISheet sheet = workbook.CreateSheet(dt.TableName); if (isColumnWritten) { IRow row = sheet.CreateRow(0 ); for (int j = 0 ; j < dt.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(dt.Columns[j].ColumnName); } } for (int i = 0 ; i < dt.Rows.Count; ++i) { IRow row = sheet.CreateRow(isColumnWritten ? i + 1 : i); for (int j = 0 ; j < dt.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString()); } } } workbook.Write(fs); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return false ; } } return true ; } private static DataTable BuildDataTable (IRow Row ) { DataTable result = null ; if (Row.Cells.Count > 0 ) { result = new DataTable(); for (int i = 0 ; i < Row.LastCellNum; i++) { if (Row.GetCell(i) != null ) { result.Columns.Add(Row.GetCell(i).ToString()); } } } return result; } } }
获取单元格类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 private static object GetValueType (ICell cell ){ if (cell == null ) return null ; switch (cell.CellType) { case CellType.Blank: return null ; case CellType.Boolean: return cell.BooleanCellValue; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(cell)) { return cell.DateCellValue; } return cell.NumericCellValue; case CellType.String: return cell.StringCellValue; case CellType.Error: return cell.ErrorCellValue; case CellType.Formula: cell.SetCellType(CellType.String); return cell.StringCellValue; default : return "=" + cell.CellFormula; } }
NPOI读写数据、设置单元格样式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 public static int DataTableToExcel (DataTable data, string sheetName, string fileName, bool isColumnWritten = true ) { IWorkbook workbook = null ; using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (fileName.IndexOf(".xlsx" ) > 0 ) { workbook = new XSSFWorkbook(); } else if (fileName.IndexOf(".xls" ) > 0 ) { workbook = new HSSFWorkbook(); } if (workbook == null ) { return -1 ; } try { ISheet sheet = workbook.CreateSheet(sheetName); int count = 0 ; if (isColumnWritten) { IRow row = sheet.CreateRow(0 ); ICellStyle columnStyle = workbook.CreateCellStyle(); columnStyle.BorderTop = BorderStyle.Thin; columnStyle.BorderBottom = BorderStyle.Thin; columnStyle.BorderLeft = BorderStyle.Thin; columnStyle.BorderRight = BorderStyle.Thin; columnStyle.Alignment = HorizontalAlignment.Center; columnStyle.VerticalAlignment = VerticalAlignment.Center; columnStyle.FillPattern = FillPattern.SolidForeground; columnStyle.FillForegroundColor = 40 ; for (int j = 0 ; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); ICell cell = row.GetCell(j); cell.CellStyle = columnStyle; sheet.SetColumnWidth(j, 20 * 256 ); } count = 1 ; } for (int i = 0 ; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.BorderBottom = BorderStyle.Thin; cellStyle.BorderLeft = BorderStyle.Thin; cellStyle.BorderRight = BorderStyle.Thin; cellStyle.BorderTop = BorderStyle.Thin; for (int j = 0 ; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); ICell cell = row.GetCell(j); cell.CellStyle = cellStyle; } count++; } workbook.Write(fs); return count; } catch (Exception ex) { MessageBoxInfor.ShowMessageBox("Exception:" + ex.Message); return -1 ; } } }
C#-IO-文件Copy Copy() 1 2 3 4 string sourceFile = @"c:\temp\New Text Document.txt" ; string destinationFile = @"c:\temp\test.txt" ; bool isrewrite=true ; System.IO.File.Copy(sourcePath, targetPath, isrewrite);
CopyTo() 1 2 3 4 5 6 7 8 string sourceFile = @"c:\temp\New Text Document.txt" ; string destinationFile = @"c:\temp\test.txt" ; FileInfo file = new FileInfo(sourceFile); if (file.Exists) { file.CopyTo(destinationFile, true ); }
文件流实现Copy 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 #region 拷贝操作 private void button3_Click (object sender, EventArgs e ){ OpenFileDialog ofd = new OpenFileDialog(); DialogResult res = ofd.ShowDialog(); if (res == DialogResult.OK) { if (!string .IsNullOrEmpty(ofd.FileName)) { FileStream streamRead = new FileStream(ofd.FileName, FileMode.Open); byte [] data = new byte [1024 * 1024 ]; int length = 0 ; SaveFileDialog sfd = new SaveFileDialog(); DialogResult sres = sfd.ShowDialog(); if (sres == DialogResult.OK) { if (!string .IsNullOrEmpty(ofd.FileName)) { FileStream streamWrite = new FileStream(sfd.FileName, FileMode.Create); do { length = streamRead.Read(data, 0 , data.Length); for (int i = 0 ; i < length; i++) { data[i] = (byte )(255 - data[i]); } streamWrite.Write(data, 0 , length); } while (length == data.Length); } } } } } #endregion
C#NPOI实现Excel文件复制 1 2 3 4 5 6 7 8 9 10 11 12 string filepath = @"C:\Users\Administrator\Desktop\测试.xlsx" ;FileStream fs = new FileStream(filepath,FileMode.Open,FileAccess.Read); IWorkbook wb = new XSSFWorkbook(fs); fs.Close(); string outFilePath = @"C:\Users\Administrator\Desktop\输出测试.xlsx" ; FileStream outFs = new FileStream(outFilePath,FileMode.Create,FileAccess.Write); wb.Write(outFs); outFs.Close(); wb.Close();
复制模板问价并写入内容 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 private void uiSyCreateExcel_Click (object sender, EventArgs e ) { try { FolderBrowserDialog folder = new FolderBrowserDialog(); if (folder.ShowDialog() == DialogResult.OK) { string ExportDir = folder.SelectedPath + "\\数据导出" + DateTime.Now.ToString("yyyyMMddHHmmss" ) + ".xlsx" ; string filepath = @"DataBase\Report.xlsx" ; FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); IWorkbook wb = new XSSFWorkbook(fs); fs.Close(); FileStream outFs = new FileStream(ExportDir, FileMode.Create, FileAccess.Write); wb.Write(outFs); outFs.Close(); wb.Close(); bool WriteSymbol = ExcelHelper.WriteDataTableToExcel(dt, ExportDir, false ,dt.Rows.Count); if (WriteSymbol==true ) { MessageBox.Show("导出成功,文件存储在" + ExportDir + "。" ); } else { MessageBox.Show("导出失败,请检查导出文件是否处于打开状态或查看日志文件" ); } } } catch (Exception ex) { FileOperate.WriteLog(ex); } }
输出带列名的DataTable数据表并调整Excel内容格式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 public static int DataTableToExcel (DataTable data, string sheetName, string fileName, bool isColumnWritten = true ) { IWorkbook workbook = null ; using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (fileName.IndexOf(".xlsx" ) > 0 ) { workbook = new XSSFWorkbook(); } else if (fileName.IndexOf(".xls" ) > 0 ) { workbook = new HSSFWorkbook(); } if (workbook == null ) { return -1 ; } try { ISheet sheet = workbook.CreateSheet(sheetName); int count = 0 ; if (isColumnWritten) { IRow row = sheet.CreateRow(0 ); ICellStyle columnStyle = workbook.CreateCellStyle(); columnStyle.BorderTop = BorderStyle.Thin; columnStyle.BorderBottom = BorderStyle.Thin; columnStyle.BorderLeft = BorderStyle.Thin; columnStyle.BorderRight = BorderStyle.Thin; columnStyle.Alignment = HorizontalAlignment.Center; columnStyle.VerticalAlignment = VerticalAlignment.Center; columnStyle.FillPattern = FillPattern.SolidForeground; columnStyle.FillForegroundColor = 40 ; for (int j = 0 ; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); ICell cell = row.GetCell(j); cell.CellStyle = columnStyle; sheet.SetColumnWidth(j, 20 * 256 ); } count = 1 ; } for (int i = 0 ; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.BorderBottom = BorderStyle.Thin; cellStyle.BorderLeft = BorderStyle.Thin; cellStyle.BorderRight = BorderStyle.Thin; cellStyle.BorderTop = BorderStyle.Thin; for (int j = 0 ; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); ICell cell = row.GetCell(j); cell.CellStyle = cellStyle; } count++; } workbook.Write(fs); return count; } catch (Exception ex) { MessageBoxInfor.ShowMessageBox("Exception:" + ex.Message); return -1 ; } } }
Excel单元格中写入图片 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 private void ExcelHelper () { string ExportPath = "D:\\QuickTest\\test.xlsx" ; IWorkbook workbook = null ; using (FileStream fs = new FileStream(ExportPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (ExportPath.IndexOf(".xlsx" ) > 0 ) { workbook = new XSSFWorkbook(); } else if (ExportPath.IndexOf(".xls" ) > 0 ) { workbook = new HSSFWorkbook(); } if (workbook == null ) { return ; } try { ISheet sheet = workbook.CreateSheet("PictureTest" ); sheet.SetColumnWidth(0 , 18 * 256 ); sheet.SetColumnWidth(1 , 18 * 256 ); IRow rowHeader = sheet.CreateRow(0 ); rowHeader.CreateCell(0 , CellType.String).SetCellValue("测试表头_1" ); rowHeader.CreateCell(1 , CellType.String).SetCellValue("测试表头_2" ); IRow rowFirstRow = sheet.CreateRow(1 ); rowFirstRow.Height = 80 * 40 ; rowFirstRow.CreateCell(0 , CellType.String).SetCellValue("测试内容" ); byte [] picByte = File.ReadAllBytes("D:\\BoiledYakult\\01壁纸图片\\backiee-246720.jpg" ); int PictureIndex = workbook.AddPicture(picByte, PictureType.JPEG); if (ExportPath.IndexOf(".xlsx" ) > 0 ) { IDrawing drawing = sheet.CreateDrawingPatriarch(); IClientAnchor anchor = drawing.CreateAnchor(0 , 0 , 0 , 0 , 1 , 1 , 2 , 2 ); IPicture pict = drawing.CreatePicture(anchor, PictureIndex); } else if (ExportPath.IndexOf(".xls" ) > 0 ) { HSSFPatriarch hSSFShapes = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); HSSFClientAnchor anchor = new HSSFClientAnchor(70 , 10 , 0 , 0 , 1 , 1 , 2 , 2 ); HSSFPicture picture = (HSSFPicture)hSSFShapes.CreatePicture(anchor, PictureIndex); } workbook.Write(fs); } catch (Exception ex) { MessageBox.Show(ex.ToString()); throw ex; } } }
C#将文件读取字符串