依賴包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
完整代碼
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ExcelUtil {
//文件存放位置
private static final String FILE_PATH= "d:/tmp";
public static void main(String[] args) {
int columnNumber = 6;
int[] columnWidth = {20, 20, 20, 20, 20, 20};
String titleName = "測試";
String[] columnName = {"評審項目", "評審要點", "分值", "評審方法", "評審結果及扣分原因", "得分"};
String[][] dataList= {{"物理安全","二", "三1","四1", "五1", "六1"},
{"物理安全","二", "三1","四2", "五2", "六2"},
{"物理安全","二", "三","四3", "五3", "六3"}};
try {
//導出數據併合並上下相同的單元格
String s = exportExcelAndMerge(columnNumber, columnWidth, titleName, columnName, dataList);
//導出數據
String s1 = exportExcelAndMerge(columnNumber, columnWidth, titleName, columnName, dataList);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取excel中的數據,指定開始行,可選着指定結束行
* @param fileInputStream excel文件輸入流
* @param beginRow 取數數據的開始行
* @param endRow 取數數據的結束行 ,不指定傳入0
* @param endColl 結束列
* @return 以二位數組的形式返回所有數據
* @throws Exception
*/
public static List<String[]> getExcel(FileInputStream fileInputStream,int beginRow,int endRow,int endColl) throws Exception{
List<String[]> list = new ArrayList<String[]>();
HSSFWorkbook wb = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = wb.getSheetAt(0);
if(endRow == 0 ) {
endRow = sheet.getLastRowNum();
}
for (int i = beginRow; i <= endRow; i++) {
HSSFRow row = sheet.getRow(i);
String[] cells = new String[endColl];
for (int j = 0; j < endColl; j++) {
HSSFCell cell = row.getCell(j);
try {
int type = cell.getCellType();
if(type==1) {
cells[j] = cell.getStringCellValue();
}else if(type==0) {
cells[j] = String.valueOf(cell.getNumericCellValue());
if(cells[j].substring(cells[j].length()-2, cells[j].length()).equals(".0")) {
cells[j] = cells[j].substring(0,cells[j].length()-2);
}
}else {
cells[j] = "";
}
} catch (Exception e) {
cells[j] = "";
}
}
list.add(cells);
}
fileInputStream.close();
return list;
}
/**
* 獲取excel中的數據,指定開始行,結束行,指定列
* @param fileInputStream excel文件輸入流
* @param columnNumber int[]需要取的列的序號
* @param beginRow 取數數據的開始行
* @param endRow 指定取數數據的結束行 ,不指定則出入0
* @return
* @throws Exception
*/
public static List<String[]> getExcel(FileInputStream fileInputStream,int[] columnNumber,int beginRow,int endRow) throws Exception{
List<String[]> list = new ArrayList<String[]>();
HSSFWorkbook wb = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = wb.getSheetAt(0);
if(endRow == 0 ) {
endRow = sheet.getLastRowNum();
}
for (int i = beginRow; i <= endRow; i++) {
HSSFRow row = sheet.getRow(i);
String[] cells = new String[columnNumber.length];
for (int j = 0; j < columnNumber.length; j++) {
HSSFCell cell = row.getCell(columnNumber[j]);
try {
int type = cell.getCellType();
if(type==1) {
cells[j] = cell.getStringCellValue();
}else if(type==0) {
cells[j] = String.valueOf(cell.getNumericCellValue());
if(cells[j].substring(cells[j].length()-2, cells[j].length()).equals(".0")) {
cells[j] = cells[j].substring(0,cells[j].length()-2);
}
}else {
cells[j] = "";
}
} catch (Exception e) {
cells[j] = "";
}
}
list.add(cells);
}
return list;
}
/**
* 導出數據成excel
* @param columnNumber 列數量
* @param columnWidth 各列寬
* @param titleName 標題
* @param columnName 各列名
* @param dataList 數據
* @return
*/
public static String ExportExcel(Integer columnNumber,int[] columnWidth,String titleName,String[] columnName,String[][] dataList) throws Exception{
// 第一步,創建一個webbook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("sheetname");
for (int i = 0; i < columnNumber; i++){
sheet.setColumnWidth(i, columnWidth[i] * 270); // 單獨設置每列的寬
}
// 第三步 , 創建第0行 也就是標題
HSSFRow row1 = sheet.createRow((int) 0);
row1.setHeightInPoints(45); // 設備標題的高度
//創建標題的單元格樣式style2以及字體樣式
HSSFFont fontStyle2 = getFontStyle(wb, true, "宋體", (short)15);
HSSFCellStyle style2 = getHeadCellStyle(wb, fontStyle2);
// 創建標題第一列
HSSFCell cell1 = row1.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1)); // 合併第0到第11列
cell1.setCellValue(titleName); // 設置值標題
cell1.setCellStyle(style2); // 設置標題樣式
// 創建第1行 也就是表頭
HSSFRow row = sheet.createRow((int) 1);
row.setHeightInPoints(37);// 設置表頭高度
//設置表頭單元格樣式以及字體樣式
HSSFFont fontStyle = getFontStyle(wb, true, "宋體", (short)13);
HSSFCellStyle style = getHeadCellStyle(wb, fontStyle);
//創建表頭的列
for (int i = 0; i < columnNumber; i++){
HSSFCell cell = row.createCell(i);
cell.setCellValue(columnName[i]);
cell.setCellStyle(style);
}
//創建數據單元格樣式 :自動換行 ,上下/左右居
HSSFCellStyle cellStyle = getCellStyle(wb, null);
//創建單元格,並設置值
for(int i = 0; i < dataList.length; i++){
row = sheet.createRow((int) i + 2);
row.setHeightInPoints(20);//行高
HSSFCell datacell = null;
for (int j = 0; j < columnNumber; j++){
datacell = row.createCell(j);
datacell.setCellValue(dataList[i][j]);
datacell.setCellStyle(cellStyle);
}
}
// 第五步,將文件存到指定位置
String filePath = saveFile(wb,titleName);
return filePath;
}
/**
* 導出數據成excel,併合並上下相同的單元格
* @param columnNumber 列數量
* @param columnWidth 各列寬
* @param titleName 標題
* @param columnName 各列名
* @param dataList 數據
* @return
*/
public static String exportExcelAndMerge(Integer columnNumber,int[] columnWidth,String titleName,String[] columnName,String[][] dataList) throws Exception{
// 第一步,創建一個webbook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("sheetName");
for (int i = 0; i < columnNumber; i++){
sheet.setColumnWidth(i, columnWidth[i] * 270); // 單獨設置每列的寬
}
// 第三步 , 創建第0行 也就是標題
HSSFRow row1 = sheet.createRow((int) 0);
row1.setHeightInPoints(45); // 設備標題的高度
//創建標題的單元格樣式style2以及字體樣式
HSSFFont fontStyle2 = getFontStyle(wb, true, "宋體", (short)15);
HSSFCellStyle style2 = getHeadCellStyle(wb, fontStyle2);
// 創建標題第一列
HSSFCell cell1 = row1.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1)); // 合併第0到第11列
cell1.setCellValue(titleName); // 設置值標題
cell1.setCellStyle(style2); // 設置標題樣式
// 創建第1行 也就是表頭
HSSFRow row = sheet.createRow((int) 1);
row.setHeightInPoints(37);// 設置表頭高度
//設置表頭單元格樣式以及字體樣式
HSSFFont fontStyle = getFontStyle(wb, true, "宋體", (short)13);
HSSFCellStyle style = getHeadCellStyle(wb, fontStyle);
//創建表頭的列
for (int i = 0; i < columnNumber; i++){
HSSFCell cell = row.createCell(i);
cell.setCellValue(columnName[i]);
cell.setCellStyle(style);
}
//創建數據單元格樣式 :自動換行 ,上下/左右居
HSSFCellStyle cellStyle = getCellStyle(wb, null);
int[] k = new int[columnNumber];
//創建單元格,並設置值
for(int i = 0; i < dataList.length; i++){
row = sheet.createRow((int) i + 2);
row.setHeightInPoints(20);//行高
HSSFCell datacell = null;
for (int j = 0; j < columnNumber; j++){
datacell = row.createCell(j);
datacell.setCellValue(dataList[i][j]);
datacell.setCellStyle(cellStyle);
//合併上下相同的單元格
if(i != 0){
boolean isEquel = dataList[i][j].equals(dataList[i-1][j]) && (! "".equals(dataList[i][j]));
if (isEquel) {//上下相同時,該列數量+1
k[j] = k[j]+1;
}else{//上下不相同
if(k[j] > 0){//該列之前有相同的,進行合併,並將相同數初始化爲0
sheet.addMergedRegion(new CellRangeAddress(i+2-k[j]-1, i+2-1, j, j));
k[j] = 0;
}
}
//到最後一,判斷是否有相同的,進行合併
if (i == dataList.length-1 ){
if(k[j] > 0){
sheet.addMergedRegion(new CellRangeAddress(i+2-k[j], i+2, j, j));
k[j] = 0;
}
}
}
}
}
// 第五步,將文件存到指定位置
String filePath = saveFile(wb,titleName);
return filePath;
}
/**
* 標題單元格樣式
* @param wb HSSFWorkbook 對象
* @param font HSSFFont字體樣式
* @return
*/
private static HSSFCellStyle getHeadCellStyle(HSSFWorkbook wb, HSSFFont font) {
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
if(font!=null) {
style.setFont(font);
}
return style;
}
/**
* 數據單元格樣式
* @param wb
* @param font
* @return
*/
private static HSSFCellStyle getCellStyle(HSSFWorkbook wb, HSSFFont font) {
HSSFCellStyle style = wb.createCellStyle();
style.setWrapText(true);// 設置自動換行
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 創建一個上下居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
// 設置邊框
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
if(font!=null) {
style.setFont(font);
}
return style;
}
/**
* 獲得字體樣式
* @param wb HSSFWorkbook對象
* @param bold 是否粗體
* @param fontName 字體類型
* @param fontSize 字體大小
* @return
*/
private static HSSFFont getFontStyle(HSSFWorkbook wb,boolean bold,String fontName,short fontSize) {
HSSFFont headerFont = (HSSFFont) wb.createFont(); // 創建字體樣式
if(bold) {
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字體加粗
}
headerFont.setFontName(fontName); // 設置字體類型
headerFont.setFontHeightInPoints(fontSize); // 設置字體大小
return headerFont;
}
/**
* 保存文件
* @param wb
* @param fileName
* @return
*/
private static String saveFile(HSSFWorkbook wb,String fileName) throws Exception {
String filePath="";
//根據如期生成文件相對路徑
Date createtime = new Date();
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
String path = "export" + File.separatorChar + formater.format(createtime);
File targetFile = new File(FILE_PATH + File.separatorChar, path);
//判斷文件夾是否存在,不存在則創建
if (!targetFile.exists()) {
targetFile.mkdirs();
}
//生成文件名
//文件存放路勁
String fileStr = FILE_PATH + File.separatorChar + path + File.separatorChar +fileName;
filePath = fileStr+ ".xls";
File file=new File(filePath);
int i=1;
//判斷文件是否存在,存在則文件名稱加序號
while(file.exists()) {
filePath=fileStr+i+".xls";
file=new File(filePath);
i++;
}
FileOutputStream fout = new FileOutputStream(file);
wb.write(fout);
String str = "導出" + filePath + "成功!";
fout.close();
return filePath;
}
}
示例
文件位置在d:/tmp\export\下