在java开发中,有时需要创建需要将数据库查询结果导入到excel表格中,这时候就需要先创建excel,然后将数据库查询的字段循环插入到excel对应的列中即可。
public class Demo(){
@Autowired
private DemoMapper demoMapper;
//创建excel并将数据库查询结果导入到excel方法 createExcel()
public void createExcel(){
File file = new File(/home/vlog/统计表.xls);
//创建一个webbook,对应一个excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//在webbook中添加一个sheet
HSSFSheet sheet =wb.createSheet("统计表");
//在sheet中添加表头第0行
HSSFRow row = sheet.creatRow(0);
//创建单元格,并设置表头内容,格式为居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
row.createCell(0).setCellValue("日期");
row.createCell(1).setCellValue("账号");
row.createCell(2).setCellValue("电话");
List<DemoBean> list = demoMapper.queryReocord();
if (list.size() >0){
for (int i =0; i < list.size(); i++){
//从第二行开始创建行,第一行是表头
row = sheet.creatRow(i+1);
if (list.get(0).getDate()!= null){
row.createCell(0).setCellValue(list.get(0).getDate())
}
if (list.get(0).getAcct()!= null){
row.createCell(1).setCellValue(list.get(0).getAcct())
}
if (list.get(0).getTel()!= null){
row.createCell(2).setCellValue(list.get(0).getTel())
}
}
}
//将数据写入到excel表格中
try(FileOutputStream output = new try(FileOutputStream(file)){
wb.write(output);
output.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
上文中用到的DemoBean实体类,是需要查询的数据库的表的实体,根据实际的情况替换成自己的实体类就行了,本文中的内容如下:
@Data
@Entity
@TableName("DEMO_TABLE")
public class DemoBean{
private String date;
private String acct;
private String tel;
}
上文中用到的DemoMapper类,为对应的数据库表的mapper类,具体到本文中,如下:
public interface DemoMapper{
List<DemoBean> queryReocord();
}
如上就完成了excel创建,并将数据库查询结果写入到excel功能。