通过java将数据写入Excel文件中
需要引入poi包
/**
*
* 创建Workbook对象
*/
public Workbook createWorkbook(String path) {
if (path.toLowerCase().endsWith("xls")) {
return new HSSFWorkbook();
} else if (path.toLowerCase().endsWith("xlsx")) {
return new XSSFWorkbook();
} else {
return null;
}
}
/**
*
* 读取Workbook对象
*/
public Workbook readWorkbook(String path) throws IOException {
FileInputStream in = new FileInputStream(path);
Workbook workbook = null;
if (path.toLowerCase().endsWith("xls")) {
workbook = new HSSFWorkbook(in);
} else if (path.toLowerCase().endsWith("xlsx")) {
workbook = new XSSFWorkbook(in);
}
in.close();
return workbook;
}
/**
*
* 获取Workbook对象
*/
public Workbook getWorkbook(String path) throws IOException {
File file = new File(path);
if (file.exists()) {
return readWorkbook(path);
} else {
return createWorkbook(path);
}
}
/**
*
* 写标题
*/
public void writeTitle(Workbook workbook, ArrayList
list) {
//生成一个表格
Sheet sheet = workbook.createSheet();
//设置表格默认列宽度为20个字符
sheet.setDefaultColumnWidth(20);
//生成一个样式,用来设置标题样式
CellStyle style = workbook.createCellStyle();
//设置这些样式
style.setFillForegroundColor(IndexedColors.SKY_BLUE.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
style.setAlignment(CellStyle.ALIGN_CENTER);
//生成一个字体
Font font = workbook.createFont();
font.setColor(IndexedColors.VIOLET.index);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//把字体应用到当前的样式
style.setFont(font);
//产生表格标题行
Row row = sheet.createRow(0);
for (int i = 0; i < list.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(list.get(i));
}
}
/**
*
* 写内容
*/
public void writeContent(Workbook workbook, ArrayList
list) {
Sheet sheet = workbook.getSheetAt(0);
//生成并设置一个样式,用于设置内容样式
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 生成另一个字体
Font font2 = workbook.createFont();
font2.setBoldweight(Font.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style.setFont(font2);
//产生表格数据行
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
for (int i = 0; i < list.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(list.get(i));
}
}
/**
*
* 输出到文件中
*/
public void printWorkbook(Workbook workbook, String path) throws IOException {
FileOutputStream out = new FileOutputStream(path);
out.flush();
workbook.write(out);
out.close();
}