···
/**
- 项目名称:m2m
- 文件名称: ExcelUtil.java
package com.syfoxconn.admin.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.;
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.;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
/**
- EXCEL 操作工具类。
- @author Administrator
*/
public class ExcelUtil {
private static final Logger logger = Logger.getLogger(ExcelUtil.class);
public static String[] getSheetNames(String fullFileName) {
if (StringUtils.isBlank(fullFileName)) {
logger.error("未指定文件名称。");
return null;
}
if (!fullFileName.endsWith(".xls") && !fullFileName.endsWith(".xlsx") &&
!fullFileName.endsWith(".xlsm")) {
logger.error("【" + fullFileName + "】不是 excel 文件。");
return null;
}
File file = new File(fullFileName);
if (!file.exists()) {
logger.error("文件【" + fullFileName + "】不存在。");
return null;
}
HSSFWorkbook hssfWb = null;
XSSFWorkbook xssfWb = null;
FileInputStream fis = null;
int num;
String[] result;
try {
fis = new FileInputStream(file);
if (fullFileName.endsWith(".xls")) {
hssfWb = new HSSFWorkbook(fis);
num = hssfWb.getNumberOfSheets();
result = new String[num];
for (int i = 0; i < num; i++) {
result[i] = hssfWb.getSheetName(i);
}
hssfWb.close();
hssfWb = null;
} else {
xssfWb = new XSSFWorkbook(fis);
num = xssfWb.getNumberOfNames();
result = new String[num];
for (int i = 0; i < num; i++) {
result[i] = xssfWb.getSheetName(i);
}
xssfWb.close();
xssfWb = null;
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
logger.error("读取文件【" + fullFileName + "】时发生了异常", e);
return null;
}
return result;
}
public static String[][] readFromExcel(String fullFileName) {
return readFromExcel(fullFileName, 0);
}
public static String[][] readFromExcel(String fullFileName, ExcelReadConfig ioConfig) {
return readFromExcel(fullFileName, 0, ioConfig);
}
public static String[][] readFromExcel(String fullFileName, String sheetName) {
return readFromExcel(fullFileName, sheetName, null);
}
public static String[][] readFromExcel(String fullFileName, String sheetName, ExcelReadConfig ioConfig) {
if (StringUtils.isBlank(fullFileName)) {
logger.error("未指定文件名称。");
return null;
}
if (!fullFileName.endsWith(".xls") && !fullFileName.endsWith(".xlsx") &&
!fullFileName.endsWith(".xlsm")) {
logger.error("【" + fullFileName + "】不是 excel 文件。");
return null;
}
File file = new File(fullFileName);
if (!file.exists()) {
logger.error("文件【" + fullFileName + "】不存在。");
return null;
}
HSSFWorkbook hssfWb = null;
XSSFWorkbook xssfWb = null;
FileInputStream fis = null;
int sheetIndex = -1;
try {
fis = new FileInputStream(file);
if (fullFileName.endsWith(".xls")) {
hssfWb = new HSSFWorkbook(fis);
sheetIndex = hssfWb.getSheetIndex(sheetName);
hssfWb.close();
hssfWb = null;
} else {
xssfWb = new XSSFWorkbook(fis);
sheetIndex = xssfWb.getSheetIndex(sheetName);
xssfWb.close();
xssfWb = null;
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
logger.error("读取文件【" + fullFileName + "】时发生了异常", e);
return null;
}
if (sheetIndex < 0) {
logger.error("文件【" + fullFileName + "】中不存在 sheet 【" + sheetName + "】");
return null;
}
return readFromExcel(fullFileName, sheetIndex, ioConfig, false);
}
public static String[][] readFromExcel(String fullFileName, int sheetIndex) {
return readFromExcel(fullFileName, sheetIndex, null);
}
public static String[][] readFromExcel(String fullFileName, int sheetIndex, ExcelReadConfig ioConfig) {
return readFromExcel(fullFileName, sheetIndex, ioConfig, true);
}
private static String[][] readFromExcel(String fullFileName, int sheetIndex, ExcelReadConfig ioConfig, boolean doInvalidFileCheck) {
File file = new File(fullFileName);
if (doInvalidFileCheck) {
if (StringUtils.isBlank(fullFileName)) {
logger.error("未指定文件名称。");
return null;
}
if (!fullFileName.endsWith(".xls") && !fullFileName.endsWith(".xlsx") &&
!fullFileName.endsWith(".xlsm")) {
logger.error("【" + fullFileName + "】不是 excel 文件。");
return null;
}
if (!file.exists()) {
logger.error("文件【" + fullFileName + "】不存在。");
return null;
}
}
HSSFWorkbook hssfWb = null;
XSSFWorkbook xssfWb = null;
Sheet sheet = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
if (fullFileName.endsWith(".xls")) {
hssfWb = new HSSFWorkbook(fis);
sheet = hssfWb.getSheetAt(sheetIndex);
} else {
xssfWb = new XSSFWorkbook(fis);
sheet = xssfWb.getSheetAt(sheetIndex);
}
if (sheet == null) {
logger.error("索引越界【" + sheetIndex + "】");
}
} catch (Exception e) {
logger.error("读取文件【" + fullFileName + "】时发生了异常", e);
return null;
}
int startRowIdx = 0;
int endRowIdx = -1;
int startColIdx = 0;
int endColIdx = -1;
if (ioConfig != null) {
startRowIdx = ioConfig.getStartRowIndex() < 0 ? 0 : ioConfig.getStartRowIndex();
endRowIdx = ioConfig.getEndRowIndex() < 0 ? -1 : ioConfig.getEndRowIndex();
startColIdx = ioConfig.getStartColumnIndex() < 0 ? 0 : ioConfig.getStartColumnIndex();
endColIdx = ioConfig.getEndColumnIndex() < 0 ? -1 : ioConfig.getEndColumnIndex();
}
if (endRowIdx == -1) {
endRowIdx = sheet.getLastRowNum();
}
int rowCount = endRowIdx - startRowIdx + 1;
if (rowCount <= 0) {
return null;
}
int colCount = endColIdx - startColIdx + 1;
if (endColIdx != -1 && colCount <= 0) {
return null;
}
String[][] result = new String[rowCount][];
String[] rowData;
Row row = null;
Cell cell = null;
int colCountPerRow = 0;
int realEndColIdx = 0;
int realStartColIdx = 0;
for (int i = startRowIdx; i <= endRowIdx; i++) {
row = sheet.getRow(i);
if (row == null) {
result[i - startRowIdx] = new String[0];
continue;
}
// getLastCellNum():取得最后一列的序号,该值为索引值 + 1。
colCountPerRow = row.getLastCellNum();
if (colCountPerRow <= 0) {
result[i - startRowIdx] = new String[0];
continue;
}
if (colCountPerRow < startColIdx + 1) {
result[i - startRowIdx] = new String[0];
continue;
}
realStartColIdx = startColIdx;
if (colCountPerRow < endColIdx + 1) {
realEndColIdx = colCountPerRow;
} else {
realEndColIdx = colCountPerRow - 1;
}
rowData = new String[realEndColIdx - realStartColIdx + 1];
result[i - startRowIdx] = rowData;
for (int j = realStartColIdx; j <= realEndColIdx; j++) {
cell = row.getCell(j);
if (cell == null) {
rowData[j] = null;
} else {
int type = cell.getCellType();
switch (type) {
case Cell.CELL_TYPE_BLANK :
rowData[j] = "";
break;
case Cell.CELL_TYPE_BOOLEAN :
rowData[j] = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR :
rowData[j] = "";
break;
case Cell.CELL_TYPE_FORMULA :
try {
rowData[j] = String.valueOf(cell.getNumericCellValue());
} catch (Exception e) {
rowData[j] = cell.getRichStringCellValue().getString();
}
break;
case Cell.CELL_TYPE_NUMERIC :
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
rowData[j] = DateFormatUtils.format(date, "yyyy/MM/dd");
} else {
// 所有的浮点数都精确到4 位小数
DecimalFormat df = new DecimalFormat("#.####");
rowData[j] = df.format(cell.getNumericCellValue());
// 如果是整数(以 4 个 0 结尾),则取整
if (rowData[j].endsWith("0000")) {
rowData[j] = rowData[j].substring(0, rowData[j].indexOf('.'));
}
}
break;
case Cell.CELL_TYPE_STRING :
rowData[j] = cell.getStringCellValue();
break;
default :
rowData[j] = "";
break;
}
}
}
}
try {
if (hssfWb != null) {
hssfWb.close();
}
if (xssfWb != null) {
xssfWb.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
logger.error("文件【" + fullFileName + "】关闭时发生了异常。");
}
return result;
}
public static String writeToExcel(List<Object[]> dataList, String templateFile) {
String tempPath = System.getProperty("java.io.tmpdir");
String tempFileName = UUID.randomUUID().toString();
String tempFile = tempPath + "\\" + tempFileName;
if (templateFile.endsWith(".xlsx")) {
tempFile += ".xlsx";
} else if (templateFile.endsWith(".xls")) {
tempFile += ".xls";
} else if (templateFile.endsWith(".xlsm")) {
tempFile += ".xlsm";
}
if (writeToExcel(dataList, tempFile, templateFile)) {
return tempFile;
} else {
return null;
}
}
public static boolean writeToExcel(List<Object[]> dataList, String fileName, String templateFile) {
return writeToExcel(dataList, fileName, templateFile, null);
}
public static boolean writeToExcel(List<Object[]> dataList, String fileName, String templateFile, ExcelWriteConfig config) {
if (StringUtils.isBlank(fileName)) {
logger.error("未指定导出文件名。");
return false;
}
if (StringUtils.isBlank(templateFile)) {
logger.error("未指定模板文件。");
return false;
}
File tplFile = new File(templateFile);
if (!tplFile.exists()) {
logger.error("指定的模板文件【" + templateFile + "】不存在。");
return false;
}
if (!templateFile.endsWith(".xls") && !templateFile.endsWith(".xlsx") && !templateFile.endsWith(".xlsm")) {
logger.error("无效的模板文件【模板文件必须是 excel 文件】。");
return false;
}
if (dataList == null || dataList.size() <= 0) {
return false;
}
if (templateFile.endsWith(".xls")) {
return writeToExcel97(dataList, fileName, templateFile, config);
} else {
return writeToExcel2003(dataList, fileName, templateFile, config);
}
}
private static boolean writeToExcel97(List<Object[]> dataList, String fileName, String templateFile, ExcelWriteConfig config) {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(templateFile));
} catch (Exception e) {
logger.error("读取模板文件【" + templateFile + "】时发生了异常。", e);
return false;
}
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(fis);
} catch (Exception e) {
logger.error("创建 HSSFWorkbook 对象时发生了异常。", e);
return false;
}
HSSFSheet sheet = wb.getSheetAt(0);
int tplRowIdx = -1;
Map<Integer, ColumnFormat> columSetMap = null;
if (config != null) {
tplRowIdx = config.getStartRowIndex() >= 0 ? config.getStartRowIndex() : -1;
columSetMap = config.getColumFormatMap();
}
HSSFRow tplRow = null;
if (tplRowIdx >= 0) {
tplRow = sheet.getRow(tplRowIdx);
}
if (tplRow == null) {
tplRow = sheet.createRow(0);
tplRowIdx = 0;
}
HSSFRow row = null;
List<HSSFCellStyle> cellStyleList = new ArrayList<HSSFCellStyle>();
for(int i = 0; i < tplRow.getLastCellNum(); i++){
cellStyleList.add(tplRow.getCell(i).getCellStyle());
}
// 填充数据。
// 按照 columSetMap 中各列定义的位置和格式填充(如果columSetMap != null)
HSSFCell cell = null;
for (int i = 0; i < dataList.size(); i++) {
row = sheet.getRow(tplRowIdx + i);
if (row == null) {
row = sheet.createRow(tplRowIdx + i);
}
for (int j = 0; j < row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
cell = row.createCell(j);
}
cell.setCellStyle(cellStyleList.get(j));
}
Object[] rowData = dataList.get(i);
if (rowData == null || rowData.length == 0) {
continue;
}
int columnLocIdx = 0;
Object obj;
for (int j = 0; j < rowData.length; j++) {
if (columSetMap != null) {
columnLocIdx = config.getColumnIndex(j);
} else {
columnLocIdx = j;
}
cell = row.getCell(columnLocIdx);
if (cell == null) {
cell = row.createCell(columnLocIdx);
}
obj = rowData[j];
if (obj == null) {
cell.setCellValue("");
} else if (obj instanceof Integer) {
cell.setCellValue((Integer)obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double)obj);
} else if (obj instanceof Float) {
cell.setCellValue((Float)obj);
} else if (obj instanceof String) {
cell.setCellValue((String)obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date)obj);
}
}
}
File outPutFile = new File(fileName);
if (outPutFile.exists()) {
outPutFile.delete();
}
try {
outPutFile.createNewFile();
wb.write(new FileOutputStream(outPutFile));
if (wb != null) {
wb.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
logger.error("关闭文件时发生了异常。", e);
return false;
}
return true;
}
private static boolean writeToExcel2003(List<Object[]> dataList, String fileName, String templateFile, ExcelWriteConfig config) {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(templateFile));
} catch (Exception e) {
logger.error("读取模板文件【" + templateFile + "】时发生了异常。", e);
return false;
}
XSSFWorkbook wb = null;
try {
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
logger.error("创建 HSSFWorkbook 对象时发生了异常。", e);
return false;
}
XSSFSheet sheet = wb.getSheetAt(0);
int tplRowIdx = -1;
Map<Integer, ColumnFormat> columSetMap = null;
if (config != null) {
tplRowIdx = config.getStartRowIndex() >= 0 ? config.getStartRowIndex() : -1;
columSetMap = config.getColumFormatMap();
}
XSSFRow tplRow = null;
if (tplRowIdx >= 0) {
tplRow = sheet.getRow(tplRowIdx);
}
if (tplRow == null) {
tplRow = sheet.createRow(0);
tplRowIdx = 0;
}
XSSFRow row = null;
List<XSSFCellStyle> cellStyleList = new ArrayList<XSSFCellStyle>();
for(int i=0; i < tplRow.getLastCellNum(); i++) {
if (tplRow.getCell(i) != null) {
cellStyleList.add(tplRow.getCell(i).getCellStyle());
} else {
cellStyleList.add(null);
}
}
// 填充数据。
// 按照 columSetMap 中各列定义的位置和格式填充(如果columSetMap != null)
XSSFCell cell = null;
for (int i = 0; i < dataList.size(); i++) {
row = sheet.getRow(tplRowIdx + i);
if (row == null) {
row = sheet.createRow(tplRowIdx + i);
}
int rowLen = row.getLastCellNum();
if (rowLen < 0) {
rowLen = cellStyleList.size();
}
for (int j = 0; j < rowLen; j++) {
cell = row.getCell(j);
if (cell == null) {
cell = row.createCell(j);
}
cell.setCellStyle(cellStyleList.get(j));
}
Object[] rowData = dataList.get(i);
if (rowData == null || rowData.length == 0) {
continue;
}
int columnLocIdx = 0;
Object obj;
for (int j = 0; j < rowData.length; j++) {
if (columSetMap != null) {
columnLocIdx = config.getColumnIndex(j);
} else {
columnLocIdx = j;
}
cell = row.getCell(columnLocIdx);
if (cell == null) {
cell = row.createCell(columnLocIdx);
}
obj = rowData[j];
if (obj == null) {
cell.setCellValue("");
} else if (obj instanceof Integer) {
cell.setCellValue((Integer)obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double)obj);
} else if (obj instanceof Float) {
cell.setCellValue((Float)obj);
} else if (obj instanceof String) {
cell.setCellValue((String)obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date)obj);
}
}
}
File outPutFile = new File(fileName);
if (outPutFile.exists()) {
outPutFile.delete();
}
try {
outPutFile.createNewFile();
wb.write(new FileOutputStream(outPutFile));
if (wb != null) {
wb.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
logger.error("关闭文件时发生了异常。", e);
return false;
}
return true;
}
public static void main(String[] args) {
/*String[][] strArr = readFromExcel("D:\\冲压车间排班计划_修改后_2015-07-16.xlsx");
if (strArr != null) {
for (int i = 0; i < strArr.length; i++) {
for (int j = 0; j < strArr[i].length; j++) {
System.out.print(strArr[i][j] + ", ");
}
System.out.println();
}
}*/
String templateFile = "D:\\tpl_sys_user.xlsx";
String fileName = "D:\\user.xlsx";
List<Object[]> dataList = new ArrayList<Object[]>();
Object[] row1 = new Object[12];
row1[0] = "jianghs";
row1[1] = "HY_0001";
row1[2] = "姜红锁";
row1[3] = "男";
row1[4] = "13840364051";
row1[5] = "13840364051";
row1[6] = "jianghs@hongyuapp.com";
row1[7] = "启用";
row1[8] = new Date();
row1[9] = "G_01,G_02";
row1[10] = "SY_01,SY_02";
row1[11] = "是";
Object[] row2 = new Object[12];
row2[0] = "zhaodn";
row2[1] = "HY_0002";
row2[2] = "赵丹娜";
row2[3] = "女";
row2[4] = "13840364051";
row2[5] = "13840364051";
row2[6] = "jianghs@hongyuapp.com";
row2[7] = "启用";
row2[8] = new Date();
row2[9] = "G_01,G_02";
row2[10] = "SY_01,SY_02";
row2[11] = "否";
Object[] row3 = new Object[12];
row3[0] = "huamj";
row3[1] = "HY_0003";
row3[2] = "华美娇";
row3[3] = "女";
row3[4] = null;
row3[5] = "13840364051";
row3[6] = "jianghs@hongyuapp.com";
row3[7] = "启用";
row3[8] = new Date();
row3[9] = "G_01,G_02";
row3[10] = "SY_01,SY_02";
row3[11] = "否";
dataList.add(row1);
dataList.add(row2);
dataList.add(row3);
ExcelWriteConfig config = new ExcelWriteConfig();
config.setStartRowIndex(3);
Map<Integer, ColumnFormat> columSetMap = new HashMap<Integer, ColumnFormat>();
columSetMap.put(1, ColumnFormat.defaultColumnFormat);
columSetMap.put(2, ColumnFormat.defaultColumnFormat);
columSetMap.put(3, ColumnFormat.defaultColumnFormat);
columSetMap.put(4, ColumnFormat.defaultColumnFormat);
columSetMap.put(5, ColumnFormat.defaultColumnFormat);
columSetMap.put(6, ColumnFormat.defaultColumnFormat);
columSetMap.put(7, ColumnFormat.defaultColumnFormat);
columSetMap.put(8, ColumnFormat.defaultColumnFormat);
columSetMap.put(9, ColumnFormat.defaultColumnFormat);
columSetMap.put(10, ColumnFormat.defaultColumnFormat);
columSetMap.put(11, ColumnFormat.defaultColumnFormat);
columSetMap.put(12, ColumnFormat.defaultColumnFormat);
columSetMap.put(13, ColumnFormat.defaultColumnFormat);
config.setColumFormatMap(columSetMap);
writeToExcel(dataList, fileName, templateFile, config);
}
}
···