Java——excel導入導出demo


1. java導入

package xx;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author CaptainFM
* @date 2019/7/2 0002 9:55
* 讀取 excel表格,兼容2003和2007
*/
public class D {

/** 總行數 */
private int totalRows = 0;

/** 總列數 */
private int totalCells = 0;

/** 錯誤信息 */
private String errorInfo;

/** 構造方法 */
public D() {}

/**
* 得到總行數
*/
public int getTotalRows() {
return totalRows;
}

/**
* 得到總列數
*/
public int getTotalCells() {
return totalCells;
}

/**
* 得到錯誤信息
*/
public String getErrorInfo() {
return errorInfo;
}

/**
*
* 驗證excel文件
* @author CaptainFM
* @param:filePath 文件完整路徑
* @return 返回 true 表示文件沒有問題
*/
public boolean validateExcel(String filePath) {
// 檢查文件名是否為空或者是否是Excel格式的文件
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorInfo = "文件不是excel格式";
return false;
}

// 檢查文件是否存在
File file = new File(filePath);

if (file == null || !file.exists()) {
errorInfo = "文件不存在";
return false;
}

return true;
}

/**
* 根據文件名讀取excel文件
* @author CaptainFM
* @param filePath 文件完整路徑
* @param ignoreRows 讀取數據忽略的行數,比喻第一行不需要讀入,忽略的行數為1
* @return:List 最后讀取的結果,數據結構:List<List<String>>
*/
public List<List<String>> read(String filePath, int ignoreRows) {

List<List<String>> dataList = new ArrayList<List<String>>();
InputStream is = null;

try {
// 驗證文件是否合法
if (!validateExcel(filePath)) {
System.out.println(errorInfo);
return null;
}

// 判斷文件的類型,是2003還是2007
boolean isExcel2003 = true;
if (isExcel2007(filePath)) {
isExcel2003 = false;
}

// 調用本類提供的根據流讀取的方法
File file = new File(filePath);
is = new FileInputStream(file);
dataList = read(is, isExcel2003, ignoreRows);
is.close();

} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {

try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}

}
}

// 返回最后讀取的結果
return dataList;
}

/**
* 根據流讀取Excel文件
* @author CaptainFM
* @param inputStream
* @param isExcel2003 是否是2003的表格(xls格式)
* @param ignoreRows 讀取數據忽略的行數,比喻第一行不需要讀入,忽略的行數為1
* @return:List
*/
public List<List<String>> read(InputStream inputStream, boolean isExcel2003, int ignoreRows) {
List<List<String>> dataList = null;
try {

// 根據版本選擇創建Workbook的方式
Workbook wb = null;

if (isExcel2003) {
wb = new HSSFWorkbook(inputStream);
} else {
wb = new XSSFWorkbook(inputStream);
}
dataList = read(wb, ignoreRows);

} catch (IOException e) {
e.printStackTrace();
}

return dataList;
}

/**
* 讀取數據
* @author CaptainFM
* @param ignoreRows 讀取數據忽略的行數,比喻第一行不需要讀入,忽略的行數為1
* @reture:List<List<String>>
*/
private List<List<String>> read(Workbook wb, int ignoreRows) {
List<List<String>> dataList = new ArrayList<List<String>>();

// 得到第一個shell
Sheet sheet = wb.getSheetAt(0);

// 得到Excel的行數
this.totalRows = sheet.getPhysicalNumberOfRows();

// 得到Excel的列數,不從表格的第一行得到列數,從忽略之后的,要讀取的第一行 獲取列數
if (this.totalRows >= 1 && sheet.getRow(ignoreRows) != null) {
this.totalCells = sheet.getRow(ignoreRows).getPhysicalNumberOfCells();
}

// 循環Excel的行,不從表格的第一行循環,去掉忽略的行數
for (int r = ignoreRows; r < this.totalRows; r++) {
Row row = sheet.getRow(r);

if (row == null) {
continue;
}

List<String> rowList = new ArrayList<String>();

// 循環Excel的列
for (int c = 0; c <= this.getTotalCells(); c++) {
Cell cell = row.getCell(c);
String cellValue = "";

if (null != cell) {
// 以下是判斷數據的類型
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 數字

// 如果數字是日期類型,就轉換成日期
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy年MM月dd日");
}
Date date = cell.getDateCellValue();
cellValue = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 31) {
// 處理自定義日期格式:yyyy年m月d日(通過判斷單元格的格式id解決,id的值是31)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
cellValue = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 單元格設置成常規
if (temp.equals("General")) {
format.applyPattern("#");
}
cellValue = format.format(value);
}
break;

case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;

case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;

case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;

case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;

case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;

default:
cellValue = "未知類型";
break;
}
}
rowList.add(cellValue);
}

// 保存第r行的第c列
dataList.add(rowList);
}
return dataList;
}

/**
* 是否是2003的excel,返回true是2003
* @author CaptainFM
* @param filePath 文件完整路徑
* @return boolean true代表是2003
*/
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}

/**
* 是否是2007的excel,返回true是2007
* @author CaptainFM
* @param filePath 文件完整路徑
* @return boolean true代表是2007
*/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}



package xx;

import java.util.List;
/**
* @author CaptainFM
* @date 2019/7/3 0003 10:07
* 測試類
*/
public class D1 {

public static void main(String[] args) throws Exception {

D re = new D();
List<List<String>> list = re.read("C:/Users/Administrator/Desktop/社保公積金薪酬字段.xlsx", 1);//忽略前1行

// 遍歷讀取結果
if (list != null) {
for (int i = 0; i < list.size(); i++) {
System.out.print("第" + (1+i) + "行");

List<String> cellList = list.get(i);
for (int j = 0; j < cellList.size(); j++) {
System.out.print(" 第" + (j + 1) + "列值:");
System.out.print(" " + cellList.get(j));
}
System.out.println();
}
}
}
}

2. java導出
package xx;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* @author CaptainFM
* @date 2019/6/25 0025 15:39
*/
//導出工作表
public class C {
public static void main(String args[]){

String[] title = {"id","name","sex"};

//創建Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//創建一個工作表sheet
Sheet sheet = workbook.createSheet();
//創建第一行
Row row = sheet.createRow(0);
Cell cell = null;
//插入第一行數據 id,name,sex
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
//追加數據
for (int i = 1; i <= 10; i++) {
Row nextrow = sheet.createRow(i);
Cell cell2 = nextrow.createCell(0);
cell2.setCellValue("a" + i);
cell2 = nextrow.createCell(1);
cell2.setCellValue("user" + i);
cell2 = nextrow.createCell(2);
cell2.setCellValue("男");
}
//需要解析的Excel文件
File file=new File("C:/Users/Administrator/Desktop/社保公積金薪酬字段.xlsx");
try {
file.createNewFile();
//將Excel內容存盤
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM