apache poi 读写xlsx文件简单示例


package com.javaexcel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Sample {
public static void main(String[] args) throws IOException {
// testRead();
// testWrite();
testChange();
}
/**
* 删除一个文件
*/
public static void delete(){
File file = new File("f:/log/poi_wirte.xlsx");
System.out.println(file.delete());
}
public static void testWrite(){
Workbook workbook = null;//一个excel文件
Sheet sheet = null;//excel一个sheet

workbook = new XSSFWorkbook();
sheet = workbook.createSheet("xssf sheet");
Row row1 = sheet.createRow(3);
Cell cell = row1.createCell(2);
cell.setCellValue("new xssf cell");
try {
workbook.write(new FileOutputStream(new File("f:/log/poi_wirte.xlsx")));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 没有发现可以修改excel文件的方法,直接覆盖后文件被损坏。只能建新文件,删除源文件,然后重命名。
* 删除源文件是需要关闭输入输出流,需要用OPCPackage的close方法。
*/
public static void testChange(){
OPCPackage opc = null;
Workbook workbook = null;
Sheet sheet = null;
try {
opc = OPCPackage.open("f:/log/poi_change.xlsx");
workbook = new XSSFWorkbook(opc);
// File f = new File("f:/log/poi_change.xlsx");
sheet = workbook.getSheetAt(0);
Row row = sheet.createRow(1);
row.createCell(0).setCellValue("a2");
row.createCell(1).setCellValue("b2");
row.createCell(2).setCellValue("c2");
workbook.write(new FileOutputStream("f:/log/poi_change2.xlsx"));
opc.close();
System.out.println(new File("f:/log/poi_change.xlsx").delete());
new File("f:/log/poi_change2.xlsx").renameTo(new File("f:/log/poi_change3.xlsx"));
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testRead(){
Workbook workBook = null;//一个excel文件
Sheet sheet = null;//excel一个sheet
try {
workBook = WorkbookFactory.create(new File("f:/log/poi_read.xlsx"));
sheet = workBook.getSheetAt(0);
for(Row row:sheet){
System.out.print(row.getRowNum()+":");
for(Cell c:row){
System.out.print("("+c.getColumnIndex()+":"+c+")");
}
System.out.print("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值