public void createExcel(){
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(keywords);
HSSFRow row = sheet.createRow((int) 0);
HSSFCellStyle style = wb.createCellStyle();
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("ID");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("摘要");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("位置");
cell.setCellStyle(style);
//关键词突出显示:标红加粗
HSSFFont fontHl = wb.createFont();
fontHl.setFontHeightInPoints((short) 14); // 字体高度
fontHl.setBold(true);
fontHl.setFontName("宋体"); // 字体
fontHl.setColor(HSSFColor.RED.index);
List<Map> docList = new ArrayList<Map>();//这里未初始化,若需要可以初始化一下.^_^
Map docMap = null;
for(int i = 0; i < docList.size(); i++){
doc = docList.get(i);
row = sheet.createRow((int) i + 1);
row.createCell((short) 0).setCellValue(String.valueOf(docMap.get("id")));
row.createCell((short) 2).setCellValue(String.valueOf(docMap.get("location")));
//摘要,这里进行转换处理
HSSFRichTextString summary = new HSSFRichTextString(String.valueOf(docMap.get("summary")));
//keywords:需要标红的字符串(出现在summary中)
Map m = hitNum(summary.getString(), "美国");
for (Object key:m.keySet()) {
int start = Integer.parseInt(m.get(key).toString());
summary.applyFont(start, start + keywords.length(), fontHl);
}
row.createCell((short) 1).setCellValue(summary);
}
FileOutputStream fout = new FileOutputStream("E:\\test.xls");
wb.write(fout);
fout.close();
}
/**
*@param source 源字符串
*@param target 目标字符串
*@return map target在source中出现的位置
*/
private Map hitNum(String source,String target){
Map m = new HashMap();
int count = 0;
int prev = -1;// 用于保存前一次的索引位置
for (int i = 0; i < source.length(); i++) {
if (source.indexOf(target, i) != -1) {
if (source.indexOf(target, i) != perv) {
perv = source.indexOf(target, i);
m.put(count++, perv);
}
}
}
return m;
}
POI处理EXCEL—个性化设计
最新推荐文章于 2024-09-03 20:52:56 发布