</pre><p> <span style="font-size:18px;"> 在工作中,真是会遇到各种问题,若是比较熟悉的题目还是容易解决,但是当遇到没有接触过的知识点,还是挺麻烦的。最近,我的工作中,需要将已经存在的excel进行读取,并将其文件导出来,我开始写了一个可以读取的文件,但是遇到版本的问题。在使用HSSF时,可以读取excel2007以及以下版本的excel文件,但是现在好多用户都已经升级到excel2010版的,所以难以解决,后来只能通过读取文件的后缀名来进行判断文件的版本。</span></p><p><span style="font-family:KaiTi_GB2312;font-size:18px;"> 首先还需要导入相应的jar包,否则文件运行时会报错。</span></p><p><span style="font-family:KaiTi_GB2312;font-size:18px;"> 需要引入的jar包如下:</span></p><p><span style="font-family:KaiTi_GB2312;font-size:18px;"> <img alt="" src="https://img-blog.csdn.net/20160112124752420?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" /></span></p><pre class="java" name="code">
具体的程序如下:
</pre><span style="font-family:SimSun;font-size:18px;"></span><pre class="java" name="code">package com.mei;
//作用:用于读取已经存在的excel文件,并将其进行导出
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.NotOLE2FileException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XssfAndHssf {
/**
* @param args
* @throws Exception
* @throws NotOLE2FileException
*/
public static void main(String[] args) throws Exception
{
//读取文件初始化
File file=null;
//文件流的初始化
FileInputStream in=null;
HSSFWorkbook hwb=null;
XSSFWorkbook xwb=null;
//文件输入路径
file=new File("F:/考勤表201511_BOM.htm");
//进行文件的版本判断
if(file.getName().endsWith(".xls"))
{
//如果是2007版本及以下的excel文件
//将文件以输入流的形式导入
in=new FileInputStream(file);
//创建新的工作簿
hwb=new HSSFWorkbook(in);
//输出文件
FileOutputStream out=null;
out=new FileOutputStream("E:/CopyOfA.xls");
hwb.write(out);
System.out.println("文件导出成功!");
//关闭文件
in.close();
out.close();
}else if(file.getName().endsWith(".xlsx"))
{
//如果是2007版本以上(不包含07版本)的excel文件
//将文件以输入流的形式导入
in=new FileInputStream(file);
//创建新的工作簿
xwb=new XSSFWorkbook(in);
//输出文件
FileOutputStream out=null;
out=new FileOutputStream("F:/CopyOfA1.xlsx");
xwb.write(out);
System.out.println("高级版本文件导出成功!");
//关闭文件
in.close();
out.close();
}else if(file.getName().endsWith(".htm")||file.getName().endsWith(".html"))
{
//如果是2007版本及以下的excel文件
//将文件以输入流的形式导入
try{
in=new FileInputStream(file);
//创建新的工作簿
hwb=new HSSFWorkbook(in);
//输出文件
FileOutputStream out=null;
out=new FileOutputStream("F:/CopyOfA.xls");
hwb.write(out);
System.out.println("文件导出成功!");
//关闭文件
in.close();
out.close();
}catch(Exception e)
{
// e.printStackTrace();
System.out.println(e.getMessage());
System.out.println("不支持此格式文件的导出!");
}
}
}
}