POI操作Excel文档

关键字:    poi       

一.POI简介

Jakarta POI 是apache的子项目,目标是处理ole2对象。它提供了一组操纵Windows文档的Java API

目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。

二.HSSF概况

HSSF 是Horrible SpreadSheet Format的缩写,也即“讨厌的电子表格格式”。也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。

HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。前者很好理解,后者比较抽象,但操作效率要高得多。

三.开始编码

1 . 准备工作

要求:JDK 1.4+POI开发包

可以到 http://www.apache.org/dyn/closer.cgi/jakarta/poi/ 最新的POI工具包

2 . EXCEL 结构

HSSFWorkbook excell 文档对象介绍
HSSFSheet excell的表单
HSSFRow excell的行
HSSFCell excell的格子单元
HSSFFont excell字体
HSSFName 名称
HSSFDataFormat 日期格式
在poi1.7中才有以下2项:
HSSFHeader sheet头
HSSFFooter sheet尾
和这个样式
HSSFCellStyle cell样式
辅助操作包括
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表

3 .具体用法实例 (采用 usermodel )

如何读Excel

读取Excel文件时,首先生成一个POIFSFileSystem对象,由POIFSFileSystem对象构造一个HSSFWorkbook,该HSSFWorkbook对象就代表了Excel文档。下面代码读取上面生成的Excel文件写入的消息字串:

代码
  1. POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));    
  2. HSSFWorkbook  wb new HSSFWorkbook(fs);    
  3.   } catch (IOException e)    
  4.   e.printStackTrace();    
  5.   }    
  6.   HSSFSheet sheet wb.getSheetAt(0);    
  7.   HSSFRow row sheet.getRow(0);    
  8.   HSSFCell cell row.getCell((short0);    
  9.   String msg cell.getStringCellValue();   
  1. POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));    
  2. HSSFWorkbook  wb new HSSFWorkbook(fs);    
  3.   } catch (IOException e)    
  4.   e.printStackTrace();    
  5.   }    
  6.   HSSFSheet sheet wb.getSheetAt(0);    
  7.   HSSFRow row sheet.getRow(0);    
  8.   HSSFCell cell row.getCell((short0);    
  9.   String msg cell.getStringCellValue();   

如何写excel,

将excel的第一个表单第一行的第一个单元格的值写成“a test”。

代码
  1. POIFSFileSystem fs =new POIFSFileSystem(new FileInputStream("workbook.xls"));    
  2.   
  3.     HSSFWorkbook wb new HSSFWorkbook(fs);    
  4.   
  5.     HSSFSheet sheet wb.getSheetAt(0);    
  6.   
  7.     HSSFRow row sheet.getRow(0);    
  8.   
  9.     HSSFCell cell row.getCell((short)0);    
  10.   
  11.     cell.setCellValue("a test");    
  12.   
  13.     // Write the output to file    
  14.   
  15.     FileOutputStream fileOut new FileOutputStream("workbook.xls");    
  16.   
  17.     wb.write(fileOut);    
  18.   
  19. fileOut.close();   

4 . 可参考文档

POI 主页:http://jakarta.apache.org/poi/,

初学者如何快速上手使用POI HSSF

http://jakarta.apache.org/poi/hssf/quick-guide.html 。

代码例子 http://blog.java-cn.com/user1/6749/archives/2005/18347.html

里面有很多例子代码,可以很方便上手。

POI的中级应该用


1、遍历workbook

代码
  1. // load源文件   
  2. POIFSFileSystem fs new POIFSFileSystem(new FileInputStream(filePath));   
  3. HSSFWorkbook wb new HSSFWorkbook(fs);   
  4. for (int 0wb.getNumberOfSheets(); i++) {   
  5.     HSSFSheet sheet wb.getSheetAt(i);   
  6.     for (int sheet.getFirstRowNum(); sheet.getLastRowNum(); ++) {   
  7.     HSSFRow row sheet.getRow(i);   
  8.             if (row != null{   
  9.         。。。操作}   
  10.        }   
  11.      }   
  12. // 目标文件   
  13. FileOutputStream fos new FileOutputStream(objectPath);   
  14. //写文件   
  15. swb.write(fos);   
  16. fos.close();  

2、得到列和单元格

代码
  1. HSSFRow row sheet.getRow(i);   
  2. HSSFCell cell row.getCell((shortj);  

3、设置sheet名称和单元格内容为中文

代码
  1. wb.setSheetName(n, "中文",HSSFCell.ENCODING_UTF_16);       
  2. cell.setEncoding((short1);   
  3. cell.setCellValue("中文");  

4、单元格内容未公式或数值,可以这样读写

代码
  1. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);   
  2. cell.getNumericCellValue()  


5、设置列宽、行高

代码
  1. sheet.setColumnWidth((short)column,(short)width);   
  2. row.setHeight((short)height);  


6、添加区域,合并单元格

代码
  1. Region region new Region((short)rowFrom,(short)columnFrom,(short)rowTo,(short)columnTo);   
  2. sheet.addMergedRegion(region);   
  3. //得到所有区域   
  4. sheet.getNumMergedRegions()  

7、常用方法
根据单元格不同属性返回字符串数值

代码
  1. public String getCellStringValue(HSSFCell cell) {   
  2.         String cellValue "";   
  3.         switch (cell.getCellType()) {   
  4.         case HSSFCell.CELL_TYPE_STRING:   
  5.             cellValue cell.getStringCellValue();   
  6.             if(cellValue.trim().equals("")||cellValue.trim().length()<=0)   
  7.                 cellValue=";   
  8.             break;   
  9.         case HSSFCell.CELL_TYPE_NUMERIC:   
  10.             cellValue String.valueOf(cell.getNumericCellValue());   
  11.             break;   
  12.         case HSSFCell.CELL_TYPE_FORMULA:   
  13.             cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);   
  14.             cellValue String.valueOf(cell.getNumericCellValue());   
  15.             break;   
  16.         case HSSFCell.CELL_TYPE_BLANK:   
  17.             cellValue=";   
  18.             break;   
  19.         case HSSFCell.CELL_TYPE_BOOLEAN:   
  20.             break;   
  21.         case HSSFCell.CELL_TYPE_ERROR:   
  22.             break;   
  23.         default:   
  24.             break;   
  25.         }   
  26.         return cellValue;   
  27.      


8、常用单元格边框格式

虚线HSSFCellStyle.BORDER_DOTTED
实线HSSFCellStyle.BORDER_THIN

代码
  1. public static HSSFCellStyle getCellStyle(short type)   
  2.          
  3.        HSSFWorkbook wb new HSSFWorkbook();   
  4.        HSSFCellStyle style wb.createCellStyle();   
  5.        style.setBorderBottom(type);//下边框    
  6.         style.setBorderLeft(type);//左边框    
  7.         style.setBorderRight(type);//右边框    
  8.         style.setBorderTop(type);//上边框    
  9.        return style;   
  10.      


9、设置字体和内容位置

代码
  1. HSSFFont  wb.createFont();   
  2. f.setFontHeightInPoints((short11);//字号   
  3. f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗   
  4. style.setFont(f);   
  5. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中   
  6. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中   
  7. style.setRotation(short rotation);//单元格内容的旋转的角度   
  8. HSSFDataFormat df wb.createDataFormat();   
  9. style1.setDataFormat(df.getFormat("0.00%"));//设置单元格数据格式   
  10. cell.setCellFormula(string);//给单元格设公式   
  11. style.setRotation(short rotation);//单元格内容的旋转的角度   
  12. cell.setCellStyle(style);   


10、插入图片

论坛里看到的
代码
  1. //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray   
  2.       ByteArrayOutputStream byteArrayOut new ByteArrayOutputStream();   
  3.       BufferedImage bufferImg ImageIO.read(new File("ok.jpg"));   
  4.       ImageIO.write(bufferImg,"jpg",byteArrayOut);   
  5. //读进一个excel模版   
  6. FileInputStream fos new FileInputStream(filePathName+"/stencil.xlt");    
  7. fs new POIFSFileSystem(fos);   
  8. //创建一个工作薄   
  9. HSSFWorkbook wb new HSSFWorkbook(fs);   
  10. HSSFSheet sheet wb.getSheetAt(0);   
  11. HSSFPatriarch patriarch sheet.createDrawingPatriarch();   
  12. HSSFClientAnchor anchor new HSSFClientAnchor(0,0,1023,255,(short0,0,(short)10,10);        
  13. patriarch.createPicture(anchor wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));  

11、设置列自动换行

   HSSFCellStyle cellStyle =  workbook.createCellStyle();
   cellStyle.setWrapText(true);
   sheet.setDefaultColumnStyle((short)0, cellStyle);

    设置列的宽度

   sheet.setColumnWidth((short)0,(short)9000);

 

  sheet.setDefaultColumnStyle((short)0, cellStyle);

  与

  sheet.setDefaultColumnWidth((short)70);冲突

  只会换行 不会设置列宽


单元格拷贝示例:


package testpoi;


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;

import org.apache.poi.hssf.util.Region;

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

/**

 * 将某SHEET页中的某几行复制到某SHEET页的某几行中。抱括被合并了的单元格。

 */

public class RowCopy {


/**

* @param args

* @throws IOException

* @throws FileNotFoundException

*/


@SuppressWarnings("deprecation")

public static void main(String[] args) {

try {

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(

"d://exlsample.xls"));

HSSFWorkbook wb = new HSSFWorkbook(fs);


// source为源sheet 页,target为目标sheet页

copyRows(wb, "source", "target", 5, 6, 20);

FileOutputStream fileOut = new FileOutputStream("d://exlsample.xls");

wb.write(fileOut);

fileOut.flush();

fileOut.close();

System.out.println("Operation finished");

} catch (Exception e) {

e.printStackTrace();

}

}


/**

* @param wb HSSFWorkbook

* @param pSourceSheetName 源sheet页名称

* @param pTargetSheetName 目标sheet页名称

* @param pStartRow 源sheet页中的起始行

* @param pEndRow  源sheet页中的结束行

* @param pPosition 目标sheet页中的开始行

*/

public static void copyRows(HSSFWorkbook wb, String pSourceSheetName,

String pTargetSheetName, int intStartRow, int intEndRow, int intPosition) {

// EXECL中的行是从1开始的,而POI中是从0开始的,所以这里要减1.

int pStartRow = intStartRow - 1;

int pEndRow = intEndRow - 1;

int pPosition = intPosition - 1;

HSSFRow sourceRow = null;

HSSFRow targetRow = null;

HSSFCell sourceCell = null;

HSSFCell targetCell = null;

HSSFSheet sourceSheet = null;

HSSFSheet targetSheet = null;

Region region = null;

int cType;

int i;

int j;

int targetRowFrom;

int targetRowTo;


if ((pStartRow == -1) || (pEndRow == -1)) {

return;

}

sourceSheet = wb.getSheet(pSourceSheetName);

targetSheet = wb.getSheet(pTargetSheetName);

System.out.println(sourceSheet.getNumMergedRegions());

// 拷贝合并的单元格

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

region = sourceSheet.getMergedRegionAt(i);

if ((region.getRowFrom() >= pStartRow)

&& (region.getRowTo() <= pEndRow)) {

targetRowFrom = region.getRowFrom() - pStartRow + pPosition;

targetRowTo = region.getRowTo() - pStartRow + pPosition;

region.setRowFrom(targetRowFrom);

region.setRowTo(targetRowTo);

targetSheet.addMergedRegion(region);

}

}

// 设置列宽

for (i = pStartRow; i <= pEndRow; i++) {

sourceRow = sourceSheet.getRow(i);

if (sourceRow != null) {

for (j = sourceRow.getLastCellNum(); j > sourceRow

.getFirstCellNum(); j--) {

targetSheet

.setColumnWidth(j, sourceSheet.getColumnWidth(j));

targetSheet.setColumnHidden(j, false);

}

break;

}

}

// 拷贝行并填充数据

for (; i <= pEndRow; i++) {

sourceRow = sourceSheet.getRow(i);

if (sourceRow == null) {

continue;

}

targetRow = targetSheet.createRow(i - pStartRow + pPosition);

targetRow.setHeight(sourceRow.getHeight());

for (j = sourceRow.getFirstCellNum(); j < sourceRow

.getPhysicalNumberOfCells(); j++) {

sourceCell = sourceRow.getCell(j);

if (sourceCell == null) {

continue;

}

targetCell = targetRow.createCell(j);

targetCell.setCellStyle(sourceCell.getCellStyle());

cType = sourceCell.getCellType();

targetCell.setCellType(cType);

switch (cType) {

case HSSFCell.CELL_TYPE_BOOLEAN:

targetCell.setCellValue(sourceCell.getBooleanCellValue());

System.out.println("--------TYPE_BOOLEAN:"

+ targetCell.getBooleanCellValue());

break;

case HSSFCell.CELL_TYPE_ERROR:

targetCell

.setCellErrorValue(sourceCell.getErrorCellValue());

System.out.println("--------TYPE_ERROR:"

+ targetCell.getErrorCellValue());

break;

case HSSFCell.CELL_TYPE_FORMULA:

// parseFormula这个函数的用途在后面说明

targetCell.setCellFormula(parseFormula(sourceCell

.getCellFormula()));

System.out.println("--------TYPE_FORMULA:"

+ targetCell.getCellFormula());

break;

case HSSFCell.CELL_TYPE_NUMERIC:

targetCell.setCellValue(sourceCell.getNumericCellValue());

System.out.println("--------TYPE_NUMERIC:"

+ targetCell.getNumericCellValue());

break;

case HSSFCell.CELL_TYPE_STRING:

targetCell

.setCellValue(sourceCell.getRichStringCellValue());

System.out.println("--------TYPE_STRING:" + i

+ targetCell.getRichStringCellValue());

break;

}


}


}


}


/**

* POI对Excel公式的支持是相当好的,但是有一个问题,如果公式里面的函数不带参数,比如now()或today(),

* 那么你通过getCellFormula()取出来的值就是now(ATTR(semiVolatile))和today(ATTR(semiVolatile)),

* 这样的值写入Excel是会出错的,这也是我上面copyRow的函数在写入公式前要调用parseFormula的原因,

* parseFormula这个函数的功能很简单,就是把ATTR(semiVolatile)删掉。

* @param pPOIFormula

* @return

*/

private static String parseFormula(String pPOIFormula) {

final String cstReplaceString = "ATTR(semiVolatile)"; //$NON-NLS-1$

StringBuffer result = null;

int index;


result = new StringBuffer();

index = pPOIFormula.indexOf(cstReplaceString);

if (index >= 0) {

result.append(pPOIFormula.substring(0, index));

result.append(pPOIFormula.substring(index

+ cstReplaceString.length()));

} else {

result.append(pPOIFormula);

}


return result.toString();

}


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Apache POI库来复制Excel文件。以下是一个简单的示例代码,可以将一个Excel文件复制到另一个Excel文件: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelCopyExample { public static void main(String[] args) throws IOException, InvalidFormatException { // 读取要复制的Excel文件 FileInputStream inputStream = new FileInputStream("source.xlsx"); Workbook sourceWorkbook = WorkbookFactory.create(inputStream); // 创建新的Excel文件 Workbook targetWorkbook = WorkbookFactory.create(true); // 将要复制的Excel文件的每个sheet复制到新文件中 for (int i = 0; i < sourceWorkbook.getNumberOfSheets(); i++) { targetWorkbook.createSheet(sourceWorkbook.getSheetName(i)); targetWorkbook.setSheetOrder(sourceWorkbook.getSheetName(i), i); targetWorkbook.cloneSheet(i); } // 将新的Excel文件保存到磁盘上 FileOutputStream outputStream = new FileOutputStream("target.xlsx"); targetWorkbook.write(outputStream); outputStream.close(); System.out.println("Excel文件复制完成!"); } } ``` 在这个示例中,我们首先读取要复制的Excel文件,并创建一个新的Excel文件。然后,我们遍历要复制的Excel文件中的每个sheet,并将其复制到新文件中。最后,我们将新文件保存到磁盘上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值