在开发中导出导入数据,我们是经常用到的,近期,公司开发中需要将指定数据导入到用户给定的EXCEL模板中,并根据要求合并单元格,在这里,我写了个简单的demo,可以概括我所用到的知识点,以供有需要的朋友借鉴。
相关DEMO下载:PoiTest
public class Test {
public static void main(String[] args) {
try{
FileInputStream fis = new FileInputStream("d:/model.xlsx");
XSSFWorkbook workBook=new XSSFWorkbook(fis);
String fileName="test_"+System.currentTimeMillis()+".xlsx";
OutputStream out=new FileOutputStream("d:/"+fileName);
XSSFCellStyle style = CellStyle.getStyle(workBook);
for(int j=0;j<2;j++){ //导出有多个sheet的workBook
XSSFSheet sheet=workBook.cloneSheet(0); //进行模板的克隆
workBook.setSheetName(j+1, "sheet"+j); //给sheet命名
int rowIndex=8;
XSSFRow row=sheet.createRow(rowIndex);
for(int i=1;i<23;i++){
XSSFCell cell=row.createCell(i);
cell.setCellValue(i);
//合并单元格,参数是起始行,结束行,起始列,结束列
sheet.addMergedRegion(new CellRangeAddress(rowIndex,rowIndex+1, i,i));
cell.setCellStyle(style); //给单元格添加样式
}
}
workBook. removeSheetAt(0); //移除workbook中的模板sheet
workBook.write(out);
fis.close();
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public class CellStyle {
public static XSSFCellStyle getStyle(XSSFWorkbook workbook) {
//设置样式;
XSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
}
原文地址:http://blog.csdn.net/ps101505138/article/details/40304161