java中数据库导出excel
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");
//将要存放数行标题的集合
List listKey =null;
//查找出数据库中所有的数据
//这里查找出自己的数据库数据
/*将数据库中的每一列都字段名取出*/
if ((list != null) && (!list.isEmpty()))
{
listKey = new ArrayList();
Map mapResult = (Map)list.get(0);
Set mapKeySet = mapResult.keySet();
String listHead = "";
Iterator iteratorKey = mapKeySet.iterator();
while (iteratorKey.hasNext()) {
listHead = (String) iteratorKey.next();
listKey.add(listHead);
}
}
//随便写一个工作表的名字
String sheetName="sheet1";
/*创建excel表*/
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(sheetName);
// 设置表格默认列宽度
sheet.setDefaultColumnWidth((short) 20);
// 产生表格标题行
XSSFRow row = sheet.createRow(0);
for (short i = 0; i < listKey.size(); i++) {
//创建第行的单元格
XSSFCell cell = row.createCell(i);
XSSFRichTextString text = new XSSFRichTextString((String) listKey.get(i));
//将取出来的字段名写入这个单元格
cell.setCellValue(text);
}
// 遍历集合数据,产生数据行
int index = 0;
//这里遍历自己的集合
for (xxx xxx : list) {
index++;
//创建一行数据
row = sheet.createRow(index);
for (int i = 0; i < listKey.size(); i++) {
//创建一列数据
XSSFCell cell = row.createCell(i);
//通过key获取所有的数据
String value = (String) pageData.get(listKey.get(i));
row.createCell(i).setCellValue(value);
}
}
/*System.out.println(o);*/
//设置文件名
String fileName ="\\"+ sdf1.format(new Date()) + sheetName + ".xlsx";
//设置路径
String folderPath="";//这里写保存的路径
String savePath = folderPath+ fileName;
// System.out.println(savePath);
//导出excel文件
OutputStream fileOut = new FileOutputStream(savePath);
workbook.write(fileOut);
fileOut.close();
前台整个按钮,写上这个链接就可以实现下载excel文件了