下载jar包网址:
http://download.csdn.net/download/demon_ll/10040537
CreateUtil类:
public static void createExcelFile(String filename, XSSFWorkbook wb) {
try {
FileOutputStream fout = new FileOutputStream(filename);
wb.write(fout);
fout.close();
fout = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public static void excelArticleFileWriter(String fileName,
List<newsStat > clist) throws IOException {
// 创建一个FileWriter对象
File file = new File(fileName);
XSSFWorkbook wb = new XSSFWorkbook();
if (file.exists()) {
InputStream instream = new FileInputStream(fileName);
wb = new XSSFWorkbook(instream);
} else {
createExcelFile(fileName, wb);
}
XSSFSheet sheet = wb.getSheet("sheet0");
if (sheet == null) {
sheet = wb.createSheet("sheet0");
}
XSSFRow row = sheet.createRow((int) 0);
int rowCount = sheet.getLastRowNum();
if (rowCount == 0) {
row = sheet.createRow((int) 0);
// HSSFCellStyle style = wb.createCellStyle();
Cell cell = row.createCell((short) 0);
// HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("关键词");
cell = row.createCell((short) 1);
cell.setCellValue("新闻");
cell = row.createCell((short) 2);
} else {
}
for (int i = 0; i < clist.size(); i++) {
ResultBean a = (ResultBean) clist.get(i);
if (a != null) {
// news; forum;blogs; press;
row = sheet.createRow((int) rowCount + i + 1);
row.createCell((short) 0).setCellValue(a.getKeyword());
row.createCell((short) 1).setCellValue(a.getNews());
}
}
try {
FileOutputStream fout = new FileOutputStream(fileName);
wb.write(fout);
fout.close();
fout = null;
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
}
Bean:
public class newsStat {
private String keyword;
private int news;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getNews() {
return nwcounts;
}
public void setNews(int news) {
this.news= news;
}
}
main:
public static void main(String[] args) throws IOException {
List<newsStat> list = new ArrayList();
for (int i = 0; i < 100; i++) {
newsStat n = new newsStat();
n.setKeyword("test" + i);
n.setNews(10);
list.add(n);
}
excelArticleFileWriter("d:\\test.xlsx", list);
}
ok,完成了