利用poi在Excel中插入

关于Excel中插入

poi提供的Class HSSFSheet 中的函数shiftRows可以把某区域的行移动,但是移动后剩下的区域却为空了。以下程序实现了按照原来的形式插入行的效果。而不是单单只是移动。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 * @author ZhangPuSheng
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here
        FileInputStream myxls = new FileInputStream("workbook.xls");
        HSSFWorkbook wb = new HSSFWorkbook(myxls);
        HSSFSheet sheet= wb.getSheetAt(0);
        int startRow=2;
        int rows =10;

        insertRow(sheet,startRow,rows);
       
        FileOutputStream myxlsout = new FileOutputStream("workbook.xls");
        wb.write(myxlsout);
        myxlsout.close();
        
    }

    private static void insertRow(HSSFSheet sheet, int startRow, int rows) {
        sheet.shiftRows(startRow, sheet.getLastRowNum(), rows, true, false);


        for (int i = 0; i < rows; i++) {
            HSSFRow sourceRow = null;//原始位置
            HSSFRow targetRow = null;//移动后位置
            HSSFCell sourceCell = null;
            HSSFCell targetCell = null;
            sourceRow = sheet.createRow(startRow);
            targetRow = sheet.getRow(startRow + rows);
            sourceRow.setHeight(targetRow.getHeight());

            for (int m = targetRow.getFirstCellNum(); m < targetRow.getPhysicalNumberOfCells(); m++) {
                sourceCell = sourceRow.createCell(m);
                targetCell = targetRow.getCell(m);
                sourceCell.setCellStyle(targetCell.getCellStyle());
                sourceCell.setCellType(targetCell.getCellType());
            }
            startRow++;
        }

    }


}

 注意:

sourceRow = sheet.createRow(startRow);和sourceCell = sourceRow.createCell(m);这两行很关键,

必须用create...,而不能用get...。因为被shiftRows后的区域是空,用get只能得到null,并且抛出异常。

 

 

  

 

你可能感兴趣的:(apache,Excel)