POI¶ÁÈ¡EXCEL½øÐÐsheet¸´ÖÆ(Ò»)

2014-11-24 01:45:34 ¡¤ ×÷Õß: ¡¤ ä¯ÀÀ: 2

Java´úÂë

/********************************************************************

*

* (C) Copyright ISFnet Japan, Ltd. 2011 All rights reserved.

*

********************************************************************/

package excel;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.util.CellRangeAddress;

/**

*

*

* @author ISFnet DALIAN muzongqin

* @since 2011/08/10

* @version 1.0

*/

public class CopyExcel {

/**

*

*

*

* @param args

* void

* @throws IOException

* @throws FileNotFoundException

*/

public static void main(String[] args) throws FileNotFoundException, IOException {

// ¥Æ¥ó¥×¥ì ¥È¤È¤Ê¤ëExcel¥Õ¥¡¥¤¥ë¤Î¥Ñ¥¹¤òÈ¡µÃ¤·¤Þ¤¹¡£

final String INVOICE_FILE = "C:\\work\\jyuchu\\ÊË \\³öÁ¦ Ʊ\\ÐÞÕý ¡¾Íê³É¡¿3_ÅÉDz Õß֪ͨ .xls";

// ¥Õ¥¡¥¤¥ë¤ò ¤ß ¤ß¤Þ¤¹¡£

POIFSFileSystem filein = new POIFSFileSystem(new FileInputStream(INVOICE_FILE));

// ¥ï ¥¯¥Ö¥Ã¥¯¤ò ¤ß ¤ß¤Þ¤¹¡£

HSSFWorkbook wb = new HSSFWorkbook(filein);

// ¥· ¥È¤ò ¤ß ¤ß¤Þ¤¹¡£

HSSFSheet sheet1 = wb.getSheet("ÅÉDz Õß֪ͨ ");

HSSFSheet sheet2 = wb.createSheet("ÅÉDz Õß֪ͨ 1");

sheet2 = copySheet(sheet1, sheet2);

FileOutputStream fileOut = new FileOutputStream("d:\\test1.xls");

wb.write(fileOut);

fileOut.close();

}

private static HSSFSheet copySheet(HSSFSheet sheetFrom, HSSFSheet sheetTo) {

// ³õÆÚ»¯

CellRangeAddress region = null;

Row rowFrom = null;

Row rowTo = null;

Cell cellFrom = null;

Cell cellTo = null;

//¥»¥ë ºÏ¤Î¥³¥Ô

for (int i = 0; i < sheetFrom.getNumMergedRegions(); i++) {

region = sheetFrom.getMergedRegion(i);

if ((region.getFirstColumn() >= sheetFrom.getFirstRowNum())

&& (region.getLastRow() <= sheetFrom.getLastRowNum())) {

sheetTo.addMergedRegion(region);

}

}

//¥»¥ë¤Î¥³¥Ô

for (int intRow = sheetFrom.getFirstRowNum(); intRow < sheetFrom.getLastRowNum(); intRow++) {

rowFrom = sheetFrom.getRow(intRow);

rowTo = sheetTo.createRow(intRow);

if (null == rowFrom)

continue;

rowTo.setHeight(rowFrom.getHeight());

for (int intCol = 0; intCol < rowFrom.getLastCellNum(); intCol++) {

//¥»¥ë·ù¤Î¥³¥Ô

sheetTo.setDefaultColumnStyle(intCol, sheetFrom.getColumnStyle(intCol));

sheetTo.setColumnWidth(intCol, sheetFrom.getColumnWidth(intCol));

cellFrom = rowFrom.getCell(intCol);

cellTo = rowTo.createCell(intCol);

if (null == cellFrom)

continue;

//¥»¥ë¥¹¥¿¥¤¥ë¤È¥¿¥¤¥×¤Î¥³¥Ô

cellTo.setCellStyle(cellFrom.getCellStyle());

cellTo.setCellType(cellFrom.getCellType());

//¥¿¥¤¥È¥ëÄÚÈݤΥ³¥Ô

if (null != cellFrom.getStringCellValue() && !"".e