您的位置:首页 > 其它

excel

2016-05-05 14:44 288 查看
excel

try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(path + "/report/model.xls"));// 声明一个工作薄
HSSFSheet sheet = workbook.createSheet(sheetName);
workbook.removeSheetAt(workbook.getSheetIndex("Sheet"));//删除默认可视sheet
HSSFCellStyle headerStyle = createHeaderStyle(workbook);
HSSFCellStyle textStyle = createTextStyle(workbook);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
fileName = "/report/"+excelName + "_"+ sdf.format(new Date()) + ".xls";
//产生表格标题行
HSSFRow row = sheet.createRow(0);
for(int i = 0; i < headers.size(); i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(headerStyle);
cell.setCellValue(headers.get(i));
int clength = headers.get(i).length()*600;
if(clength > sheet.getColumnWidth(i)){
sheet.setColumnWidth(i, clength);
}else{
sheet.setColumnWidth(i, sheet.getColumnWidth(i));
}
}

//遍历集合数据,产生数据行
if(dataset != null){
for(int index = 0; index < dataset.size() ; index++){
row = sheet.createRow(index + 1);
ExcelObj bean = (ExcelObj) dataset.get(index);
String[] strs = bean.changeMetadatas();

HSSFCell cell0 = row.createCell(0);
cell0.setCellStyle(textStyle);
cell0.setCellValue(startIndex + index + 1 + "");

for (short i = 0; i < props.size(); i++) {
HSSFCell cell = row.createCell(i + 1);
cell.setCellStyle(textStyle);
if(null == strs[i] || strs[i].equals("")){
cell.setCellValue("");
}else{
cell.setCellValue(strs[i]);
//                              sheet.autoSizeColumn(i);
}
}

}
}
//写出文件流
String nowPath = "";
if(path.endsWith(".xls")){
nowPath = path;
}else{
nowPath = path + fileName;
}
File file = new File(nowPath);
if(!file.exists()){
file.createNewFile();
}
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (Exception e) {
logger.error("异常", e);
} finally {
try {
if(fos != null)
fos.close();
} catch (IOException e) {
logger.error("异常", e);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: