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 ; }