好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用NPOI库读写Excel文件

本文实例为大家分享了C#使用NPOI库读写Excel文件的具体代码,供大家参考,具体内容如下

第一步添加程引用: 右键项目工程 — 管理 NuGet程序包 — 搜索 NOPI — 安装

对文件Excel进行操作

读取excel文件

private IWorkbook wk; ? private FileStream fs;? private void OpenExcel(string path) ? ? ? ? { ? ? ? ? ? ? StringBuilder sbr = new StringBuilder(); ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? using (fs = File.OpenRead(path)) ? //打开myxls.xls文件 ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? wk = new XSSFWorkbook(fs); ? //把xls文件中的数据写入wk中 ? ? ? ? ? ? ? ? ? ? ? for (int i = 0; i < wk.NumberOfSheets; i++) ?//NumberOfSheets是myxls.xls中总共的表数 ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ISheet sheet = wk.GetSheetAt(i); ? //读取当前表数据 ? ? ? ? ? ? ? ? ? ? ? ? ? for (int j = 0; j <= sheet.LastRowNum; j++) ?//LastRowNum 是当前表的总行数 ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? IRow row = sheet.GetRow(j); ?//读取当前行数据 ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (row != null) ? ? ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sbr.Append("-------------------------------------\r\n"); //读取行与行之间的提示界限 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? for (int k = 0; k <= row.LastCellNum; k++) ?//LastCellNum 是当前行的总列数 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ICell cell = row.GetCell(k); ?//当前表格 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (cell != null) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sbr.Append(cell.ToString()); ? //获取表格中的数据并转换为字符串类型 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? catch (Exception) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? MessageBox.Show("文件被其他应用打开,请关闭对该文件的引用!!!"); ? ? ? ? ? ? } ? ? ? ? }

修改 写入

private void SetCellValue(ISheet sheet,int row,int column,String value) ?{ ? ? ? ? ? ? ICell tmpCell = sheet.GetRow(row).GetCell(column); ? ? ? ? ? ? tmpCell.SetCellValue(value); }

保存

private void SaveExcel(String path) { ? ? ? ? ? ? //把编辑过后的工作薄重新保存为excel文件 ? ? ? ? ? ? FileStream fs2 = File.Create(path); ? ? ? ? ? ? wk.Write(fs2); ? ? ? ? ? ? fs2.Close(); ? ? ? ? ? ? MessageBox.Show("文件修改成功!!!"); ?}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于C#使用NPOI库读写Excel文件的详细内容...

  阅读:48次