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

//首先请确保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

在使用Java导出Excel文件时,由于Excel文件的数据结构比较复杂,需要使用特定的格式和方法来保存读取数据。虽然Java提供了一些API可以用来创建和编辑Excel文件,但是由于不同的版本和设置可能会导致不兼容的情况。因此,在导出Excel文件时使用另存为可以更好地保证数据的可读性和可解析性。 Java导出Excel文件时,通常使用Apache POI库来进行操作。这个库支持各种Excel文件格式,可以在Java中方便地创建、编辑和读取Excel文件中的数据。但是在使用POI库生成Excel文件时,需要注意一些细节,这些细节可能会导致文件无法正常解析。其中一个常见的问题就是版本不兼容性。 Excel文件的版本和格式非常复杂,不同的版本和设置可能会带来不同的问题。如果Excel文件不是使用最的版本(例如.xlsx格式),则可能需要使用早期版本(例如.xls格式)来保存文件。此外,在文件格式中还有一些设置,如字符编码、列宽、日期格式等,也可能会对文件的解析造成影响。 另存为是一种可行的解决方法,它可以将Java导出的Excel文件另存为一种可兼容的格式,然后再进行解析。例如,可以将Java生成的Excel文件保存为.xls格式,然后再使用解析器将其读取。这样可以避免版本和格式不兼容的问题,保证Excel文件的可读性和可解析性。 总之,在Java导出Excel文件时,建议使用另存为来保证文件的可读性和可解析性。另外,在使用POI库生成Excel文件时,需要注意一些细节,并尽可能地使用最的版本和可兼容的格式保存文件。这样才能保证生成的Excel文件可以被其他程序或人员正常解析,发挥实际作用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值