1、用到的JAR包如下(可以直接到POI官网上下载也可以在文章的附件中下载):
可能有冲突的JAR包,如果工程lib中存在,需要删除。
2、具体代码如下:
Java代码
package ;
import InputStream;
import NotFoundException;
import OutputStream;
import ception;
import utStream;
import Workbook;
import ;
import t;
import book;
import Workbook;/*3、导入和导出Excel文件类,支持2003(xls)和2007(xlsx)版本的Excel文件
@author yxm
*/
public class OperationExcelForPOI {
public static void main(String[] args) {
// 文件所在路径
String execelFile = C:/ ;
//String execelFile = C:/ ;
// 导入Excel
new OperationExcelForPOI()xcel(execelFile) ;
// 导出Excel
String expFilePath = C:/ ;
new OperationExcelForPOI()xcel(expFilePath);
}
/**
* 导入Excel
* @param execelFile
*/
public void impExcel(String execelFile){
try {
// 构造 Workbook 对象,execelFile 是传入文件路径(获得Excel工作区)
Workbook book = null;
try {
// Excel 2007获取方法
book = new XSSFWorkbook(new FileInputStream(execelFile));
} catch (Exception ex) {
// Excel 2003获取方法
book = new HSSFWorkbook(new FileInputStream(execelFile)); }
// 读取表格的第一个sheet页
Sheet sheet = heetAt(0);
// 定义 row、cell
Row row;
String cell;
// 总共有多少行,从0开始
int totalRows = astRowNum() ;
// 循环输出表格中的内容,首先循环取出行,再根据行循环取出列
for (int i = 1; i <= totalRows; i++) {
row = ow(i);
// 处理空行
if(row == null){
continue ;
}
// 总共有多少列,从0开始
int totalCells = astCellNum() ;
for (int j = irstCellNum(); j < totalCells; j++) {
// 处理空列
if(ell(j) == null){
continue ; }