npoi

NPOI可以很方便的读取写入EXCEL,且对客户机没有要求

读取excel的实例代码

 1  using (FileStream file = new FileStream("可约医院列表(网址).xls", FileMode.Open, FileAccess.Read))//参数为地址和打开方式操作方式
 2             {
 3                 HSSFWorkbook h = new HSSFWorkbook(file); 
 4                 HSSFSheet sheettemp = (HSSFSheet)h.GetSheet("sheet1");
 5                 for (int i = 1; i < sheettemp.LastRowNum; i++)
 6                 {
 7                     url = sheettemp.GetRow(i).GetCell(2).ToString();
 8                    ....  具体操作13                 }
14             }

可以当做一个datatable来操作 通过行和列来读取数据。

 

写入excel代码:

       HSSFWorkbook h = new HSSFWorkbook();
            HSSFSheet sheettemp = (HSSFSheet)h.CreateSheet("sheet1"); //创建一个对象 
Row _row = sheettemp.CreateRow(0); _row.CreateCell(0).SetCellValue("医院"); _row.CreateCell(1).SetCellValue("科室"); _row.CreateCell(2).SetCellValue("姓名"); _row.CreateCell(3).SetCellValue("擅长"); _row.CreateCell(4).SetCellValue("简介"); _row.CreateCell(5).SetCellValue("头像图片");    //excel的列头      for (int i = 0; i < dt.Rows.Count; i++) {
         //具体赋值 Row row = sheettemp.CreateRow(i + 1); row.CreateCell(0).SetCellValue(dt.Rows[i][0].ToString()); row.CreateCell(1).SetCellValue(dt.Rows[i][1].ToString()); row.CreateCell(2).SetCellValue(dt.Rows[i][2].ToString()); row.CreateCell(3).SetCellValue(dt.Rows[i][3].ToString()); row.CreateCell(4).SetCellValue(dt.Rows[i][4].ToString()); }
       AddPieChart(h);//添加图片方法 具体代码见下一代码块 sheettemp.ForceFormulaRecalculation = true;//请加上这句话 using (FileStream filewrite = new FileStream("C:\\挂号网.xls", FileMode.Create))//保存路径 { h.Write(filewrite); filewrite.Close(); }

 通过遍历 给excel赋值后 可以直接保存。这里路径可以要求用户选择或配置

 

npoi导出excel中添加图片

  string filename;
  int pictureIdx;
  HSSFClientAnchor anchor;
  Sheet sheet = workbook.GetSheet("Sheet1");
  HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
  for (int i = 0; i < dt.Rows.Count; i++)
  {
    filename = dt.Rows[i][5].ToString();
    byte[] bytes = System.IO.File.ReadAllBytes(filename);
    if (!string.IsNullOrEmpty(filename))
    {
      pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
      anchor = new HSSFClientAnchor(0,0, 700, 255, 5, i + 1, 5, i + 1);
      anchor.AnchorType = 2;
      patriarch.CreatePicture(anchor, pictureIdx);
    }
  }

方法为:AddPieChart( HSSFWorkbook workbook)

filename为你保存后的地址不可以使用网页上的引用地址。 
且HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();需在开始时就定义 否则会出现后面的图片对象覆盖之前的对象 导致最后只有一个图片的效果。
anchor = new HSSFClientAnchor(0,0, 700, 255, 5, i + 1, 5, i + 1); 参数含义 开始两个0是指边框边距  继续700和255  是指图片的大小长和宽 之后是行数和列数。

方法改成这样后 可以实现循环添加图片 不会出现只有一张图片的现象。

posted on 2014-08-05 10:46  战马  阅读(504)  评论(2)    收藏  举报

导航