GitHub
POI导出Excel,这里封装了几个方法,在监听器中调用即可。
saveFile方法主要是选保存路径,并判断文件是否已存在,list里是从数据库查询到的数据,这里就不写了
public static void saveFile(List<Map<String, Object>> list) {
File file = null;
JFileChooser jFileChooser = new JFileChooser();// 文件选择器
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xls","xls");// 文件名过滤器
jFileChooser.setFileFilter(filter);// 给文件选择器加入文件过滤器
File newfile = new File("新建文件.xls");
jFileChooser.setSelectedFile(newfile);
if (JFileChooser.APPROVE_OPTION == jFileChooser
.showSaveDialog(jFileChooser)) {
file = jFileChooser.getSelectedFile();
if(file.exists()){
int n = JOptionPane.showConfirmDialog(null,"文件已存在,是否覆盖", "提示", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (JOptionPane.YES_OPTION == n) {
writeexcel(list, file);
}
}else {
writeexcel(list, file);
}
}
writeexcel方法负责创建excel,前面4步即可,许多属性默认;并创建数据流处理数据
public static void writeexcel(List<Object[]> list, File file) {
// 1.声明工作簿
HSSFWorkbook excel = new HSSFWorkbook();
// 2.创建工作表
sheet = excel.createSheet("客户信息");
// 3.为工作表添加行
HSSFRow firstRow = sheet.createRow(0);
// 4.添加单元格
HSSFCell cells[] = new HSSFCell[3];
insertCell(list);
OutputStream out = null;
try {
out = new FileOutputStream(file);
excel.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
insertCell方法:插入数据到单元格,这里是按行插入数据;如果要按列插入数据,可以把行封装到List里,遍历数据做createRow,并把它添加到List里,在循环遍历插入数据。
public static void insertCell(List<Object[]> list) {
if (list != null) {
for (int i = 0; i < list.size(); i++) {
HSSFRow row = sheet.createRow(i);
Object[] object = list.get(i);
for (int j = 0; j < object.length; j++) {
HSSFCell cell = row.createCell(j);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(object[j]);
String str = stringBuffer.toString();
cell.setCellValue(str);
}
}
}
}