java poi 打开 excel 文件 保留格式 修改内容 另存为新文件

本文介绍如何使用Apache POI库打开并编辑Excel文件,包括打开文件、修改内容及保存新文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//首先请确保poi版本是尽量新的 我只试过两个版本 2.5的不行  然后下了3.7的就okay了。

//poi下载地址:http://www.apache.org/dyn/closer.cgi/poi/release

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

 

public class Excel
{
 private String sourceFileName;
 private String targetFileName;
 private HSSFWorkbook book;
 private HSSFSheet sheet;
 private FileInputStream fileinputstream;
 private FileOutputStream fileoutputstream;

 
 //根据需要修改sheet
 public void edit()
 {
  HSSFRow row = this.sheet.getRow(0);
  HSSFCell cell = row.getCell(0);
  cell.setCellValue("cell_edit");
  //
  //...更多修改...
  //
 }
 
 //打开excel文件
 public void openfile(String order_id)
 {
  this.sourceFileName = (Path.getRootPath() + "book_store//order_template.xls");    //Path.getRootPath() 在另外一篇日志中有~
  this.targetFileName = (Path.getRootPath() + "book_store//订单_"+order_id+".xls");
  try{
   this.fileinputstream = new FileInputStream(this.sourceFileName);
   POIFSFileSystem poifsfilesystem = new POIFSFileSystem(fileinputstream);
   this.book = new HSSFWorkbook(poifsfilesystem);
   this.sheet = this.book.getSheetAt(0); 
  }catch (Exception exception)
  {
   exception.printStackTrace();
  }
 }
 
 //关闭excel文件
 public void closeFile()
 {
  try{
   this.fileoutputstream = new FileOutputStream(this.targetFileName);
   this.book.write(this.fileoutputstream);
   fileoutputstream.flush(); 
   fileoutputstream.close();
   this.fileinputstream.close();
   } catch (Exception exception) {
    exception.printStackTrace();
      }
 }
 
 //
 //代开订单模板文件修改  再另存为一个新的excel文件
 //
 public static void main(String[] args)
 {
  Excel excel = new Excel();
  String order_id = "201101241001";
  excel.openfile(order_id);
  excel.edit();
  excel.closeFile();
 }
//////////////////////////////////// 
}


http://hi.baidu.com/online_ghost/item/67c630a843f32f786dd45502

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值