Npoi操作Excel
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Npoi操作Excel相关的知识,希望对你有一定的参考价值。
1.读取Excel的多个sheet到DataSet里面
public DataSet GetDataSetFromExcel(string path) { DataSet set = new DataSet(); FileStream fs; try { fs = new FileStream(path, FileMode.Open, FileAccess.Read); } catch (Exception) { // MessageBox.Show("文件被其他程序占用,请先关闭"); return set; } bool isCompatible = GetIsCompatible(path); IWorkbook workbook = CreateWorkbook(isCompatible, fs); //获取Excel中有几个sheet int sheetNum = workbook.NumberOfSheets; string sheetName = ""; ///Excel中的一个sheet ISheet sheet = null; int sheetIndex = -1; for (int i = 0; i < sheetNum; i++) { sheetName = workbook.GetSheetName(i); if (int.TryParse(sheetName, out sheetIndex)) { sheet = workbook.GetSheetAt(sheetIndex); } else { sheet = workbook.GetSheet(sheetName); } // 示例的excel 第一行是个大标题,第二行才是标题行,所以下面这个标题行的索引为1 set.Tables.Add(GetDataTableFromSheet(sheet, 1)); } fs.Close(); workbook = null; sheet = null; return set; } /// <summary> /// 从工作表中生成DataTable /// </summary> /// <param name="sheet">sheet 名</param> /// <param name="headerRowIndex">列标题行索引,从0开始</param> /// <returns></returns> private DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex) { DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex); ///获取excel 的列数 int cellCount = headerRow.LastCellNum; // 根据Sheet为DataTable设置列 for (int i = 0; i < cellCount; i++) { if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "") { // 如果遇到第一个空列,则不再继续向后读取 cellCount = i; break; } DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } //if (cellCount != 4) // 如果标的结构不符合要求则提示导入文件错误 //{ // //MessageBox.Show("该Excel数据异常,请确认导入的文件数据是否正确!"); // return null; //} // 获取sheet 的行数 int sheetCount = sheet.LastRowNum; for (int i = (headerRowIndex + 1); i <= sheetCount; i++) { try { // 获取一行 IRow row = sheet.GetRow(i); //如果遇到某行的第一个单元格的值为空,则不再继续向下读取 if (row != null && row.GetCell(0) != null) { // 读取sheet的一行到DataTable里面 DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { dataRow[j] = row.GetCell(j).ToString(); } table.Rows.Add(dataRow); } } catch (Exception) { } } return table; } private static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream) { if (isCompatible) { return new HSSFWorkbook(stream); } else { return new XSSFWorkbook(stream); } } private static bool GetIsCompatible(string filePath) { return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase); }
2.读取excel里面的图片
/// <summary> /// 从excel获取图片,由于excel存储图片的机制,只能根据excel中图片插入顺序导出 /// </summary> /// <param name="filepath">文件路径</param> /// <param name="savepath">图片保存路径</param> /// <param name="listPath">返回保存的图表地址list</param> /// <returns>保存图片是否成功</returns> public bool ExcelToImage(string filepath, string savepath, ref List<string> listPath) { if(!Directory.Exists(savepath)) { Directory.CreateDirectory(savepath); } try { using (FileStream fsReader = File.OpenRead(filepath)) { HSSFWorkbook wk = new HSSFWorkbook(fsReader); IList pictures = wk.GetAllPictures(); int i = 0; foreach (HSSFPictureData pic in pictures) { //if (pic.Data.Length == 19504) //跳过不需要保存的图片,其中pic.data有图片长度 // continue; string ext = pic.SuggestFileExtension();//获取扩展名 string path = string.Empty; if (ext.Equals("jpg")) { Image jpg = Image.FromStream(new MemoryStream(pic.Data));//从pic.Data数据流创建图片 path = Path.Combine(savepath, string.Format("pic{0}.jpg", i++)); jpg.Save(path);//保存 } else if (ext.Equals("png")) { Image png = Image.FromStream(new MemoryStream(pic.Data)); path = Path.Combine(savepath, string.Format("pic{0}.png", i++)); png.Save(path); } else if (ext.Equals("jpeg")) { Image png = Image.FromStream(new MemoryStream(pic.Data)); path = Path.Combine(savepath, string.Format("pic{0}.png", i++)); png.Save(path); } if (!string.IsNullOrEmpty(path)) listPath.Add(path); } } } catch (Exception ex) { Console.WriteLine("图片导出异常"); return false; } Console.WriteLine("图片导出成功,共" + listPath.Count +"个图片"); return true; }
以上是关于Npoi操作Excel的主要内容,如果未能解决你的问题,请参考以下文章
NPOI操作Excel 005:写入空Excel(Winform版)