在Excel中测试当动态增加记录时,相应图表也发生变化

最近,有一个需求,

就是有不同的Excel模板,而且可以在其中插入图片,并且图表会随着插入数据的变化而变化.

 

以下是我实现此方案的一个思路,大家可以在此基础上进行修改.

 

// 测试当动态增加记录时,相应图表也发生变化
// 这个例子程序挺实用的,大家可以在这个基础上进行修改.
// aa00aa00
package com.together.nms.dt.data.model.hibernate.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.*;

//测试当动态增加记录时,相应图表也发生变化
public class testchart {

 /**
  * 插入行
  *
  * @param wb
  *            工作簿
  * @param sheet
  *            sheet页
  * @param starRow
  *            开始行,其下面插入
  * @param rows
  *            插入的行数
  */
 public static void insertRow(HSSFWorkbook wb, HSSFSheet sheet, int starRow,
   int rows) {

  sheet.shiftRows(starRow + 1, sheet.getLastRowNum(), rows);

  starRow = starRow - 1;

  for (int i = 0; i < rows; i++) {

   HSSFRow sourceRow = null;
   HSSFRow targetRow = null;
   HSSFCell sourceCell = null;
   HSSFCell targetCell = null;

   starRow = starRow + 1;
   sourceRow = sheet.getRow(starRow);
   targetRow = sheet.createRow(starRow + 1);
   targetRow.setHeight(sourceRow.getHeight());

   for (int m = sourceRow.getFirstCellNum(); m < sourceRow
     .getPhysicalNumberOfCells(); m++) {

    sourceCell = sourceRow.getCell(m);
    targetCell = targetRow.createCell(m);

    // targetCell.setEncoding(sourceCell.getEncoding());
    targetCell.setCellStyle(sourceCell.getCellStyle());
    targetCell.setCellType(sourceCell.getCellType());
   }
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
     "d:\\Book1.xls"));
   HSSFWorkbook wb = new HSSFWorkbook(fs);
   HSSFSheet sheet = wb.getSheetAt(0);

   insertRow(wb, sheet, 3, 20);// 从第四行插入(excel中在第4行后插入),插入五行
   for (int i = 4; i < 23; i++) {
    HSSFRow row0 = sheet.getRow(i);
    for (int j = 0; j < 2; j++) {
     row0.getCell(j).setCellType(HSSFCell.CELL_TYPE_STRING);
     row0.getCell(j).setCellValue(i + j);

    }
   }

   FileOutputStream fileOut = new FileOutputStream("d:\\xxxx.xls");
   wb.write(fileOut);
   fileOut.close();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

 

例子使用的jar为poi.3.7

 

最后,把例子代码全部上传,并且带有jar包,也方便大家进行测试,呵呵!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值