您的位置:首页 > 其它

利用POI将数据导出到EXCEL模板

2014-10-20 18:10 471 查看
在开发中导出导入数据,我们是经常用到的,近期,公司开发中需要将指定数据导入到用户给定的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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: