数据库数据导出到Excel

数据库数据导出到Excel

从数据库中获取数据,使用java建立一个新建Excel,添加表头,并将数据存储到Excel表格中的对应位置上。

在新建一个Excel时,我们会需要定义一些特别的Excel格式设置,如:
定义列头格式同时自动换行
列宽度
字体类型和大小
内容格式设置为货币同时保留千分位分隔符
单元格内容靠右显示… …

上面的这些问题都在下面的代码中解决,具体方法详见注解。

public String loadDateToExcel(String workFlowNumber){
    //根据查询条件,从数据库中查询数据
    List<Traccount> traccounts = traccount.findByWorkFlowNumber(workFlowNumber);
    //创建xlsx文件格式对象,xls格式:HSSFWorkbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    //标题样式
    XSSFCellStyle setStyle = workbook.createCellStyle();
    //内容样式
    XSSFCellStyle setContentStyle = workbook.createCellStyle();

	//设置标题字体样式
	XSSFFont setFont = workbook.createFont();
	//加粗
	setFont.setBold(true);
	//字体
	setFont.setFontName("Calibri");
	//字号
	setFont.setFontHeightInPoints(short.valueOf("9").shortValue());

	//内容字体样式
	XSSFFont setContentFont = workbook.createFont();
	//字体
	setContentFont .setFontName("Calibri");
	//字号
	setContentFont .setFontHeightInPoints(short.valueOf("9").shortValue());

	//将字体样式添加到样式中
	setStyle.setFont(setFont);
	setContentStyle.setFont(setContentFont);

	//设置标题垂直居中
	setStyle.setVerticalAlignment(VerticalAlignment.CENTER);
	//设置标题水平居中
	setStyle.setAlignment(HorizontalAlignment.CENTER);
	//设置标题自动换行
	setStyle.setWrapText(true);
	//设置内容水平靠右显示
	setContentStyle.setAlignment(HorizontalAlignment.Right);

	//标题添加单元格边框    上 下 左 右
	setStyle.setBroderTop(BorderStyle.THIN);
	setStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
	setStyle.setBroderBottom(BorderStyle.THIN);
	setStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
	setStyle.setBroderLeft(BorderStyle.THIN);
	setStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
	setStyle.setBroderRight(BorderStyle.THIN);
	setStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

	//设置单元格内容格式  (常规,数字,货币,会计专用,时间 ... ...)
	XSSFDataFormat fmt = workbook.createDataFormat();
	String format = "#,##0.00";        //货币格式,带有千位分隔符,导出后需要双击单元格才会显示
	setContentStyle.setDataFormat(fmt.getFormat(format));
    
    //创建表对象
    XSSFSheet sheet = workbook.createSheet("数据Excel表名");
    //创建标题栏(第一行),参数为行下标,从0开始
    XSSFRow titleRow1 = sheet.createRow(0);
    //在标题栏1中写入数据
    XSSFCell cell = titleRow1.createCell(0);
    cell.setCellValue("标题0");
    cell.setCellStyle(setStyle);
    //设置列宽           0列     列宽13   0.62是根据选择不同字体加不同的数字,可以先不加,运行一下看看这里设置的和运行结果相差多少,然后替换此处的0.62    256是固定的
    sheet.setColumnWidth(0,(int)((13+0.62)*256));
    cell = titleRow1.createCell(1);
    cell.setCellValue("标题1");
    cell.setCellStyle(setStyle);
    // ......
    
    //设置列宽自适应  ,27为一共几列标题,因为上面设置了列宽,这里不再使用列宽自适应
    //for(int i=0;i<27;i++){
    //    sheet.autoSizeColumn(i,true);
        //sheet.autoSizeColumn(i,"列名",getBytes().length*2*256); 中文适用
    //}
    //遍历数据
    for(int i=0;i<traccounts.size();i++){
        Traccount traccount = traccounts.get(i);
        XSSFRow dateRow = sheet.createRow(i+1);
        
        //添加数据
        XSSFCell dataCell0 = dataRow.createCell(0);
        dataCell0.setCellValue(traccount.getBatchId());
        XSSFCell dataCell1 = dataRow.createCell(1);
        dataCell1.setCellValue(traccount.getCedant());
        //   ......
    }
    //创建临时文件目录
    String tempPath = "C:\\temp"+"\\Date\\"+id;
    File file = new File(tempPath);
    if(!file.exists()){
        file.mkdirs();
    }
    //临时文件路径/文件名
    String downloadPath = file +"\\" +"数据表"+DateUtil.today()+".xlsx";
    OutputStream outputStream = null;
    try{
        outputStream = new FileOutputStream(downloadPath);
        workbook.write(outputStream);
        outputStream.flush();
    }catch(Exception e){
        log.error("数据表导出失败"+e.getMessage());
        throw new BizException(ResultCodeEnum.INTERNAL_SERVER_ERROR);
    }finally{
        try{
            if(outputStream != null){
                outputStream.close();
            }
        }catch(IOException e){
            log.error("数据表关闭流失败"+e.getMessage());
            throw new BizException(ResultCodeEnum.INTERNAL_SERVER_ERROR);
        }
    }
    //将文件路径返回前端,前端根据文件路径可以直接下载到对应的文件
    return downloadPath;
}

也可将需要处理的数据查询完毕后,直接以excel文件流的形式传递回前端页面,具体步骤如下:

//查询数据,excel表构建同上
public String loadDateToExcel(String workFlowNumber){
    //根据查询条件,从数据库中查询数据
    List<Traccount> traccounts = traccount.findByWorkFlowNumber(workFlowNumber);
    //创建xlsx文件格式对象,xls格式:HSSFWorkbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    //标题样式
    XSSFCellStyle setStyle = workbook.createCellStyle();
    //内容样式
    XSSFCellStyle setContentStyle = workbook.createCellStyle();

	//设置标题字体样式
	XSSFFont setFont = workbook.createFont();
	//加粗
	setFont.setBold(true);
	//字体
	setFont.setFontName("Calibri");
	//字号
	setFont.setFontHeightInPoints(short.valueOf("9").shortValue());

	//内容字体样式
	XSSFFont setContentFont = workbook.createFont();
	//字体
	setContentFont .setFontName("Calibri");
	//字号
	setContentFont .setFontHeightInPoints(short.valueOf("9").shortValue());

	//将字体样式添加到样式中
	setStyle.setFont(setFont);
	setContentStyle.setFont(setContentFont);

	//设置标题垂直居中
	setStyle.setVerticalAlignment(VerticalAlignment.CENTER);
	//设置标题水平居中
	setStyle.setAlignment(HorizontalAlignment.CENTER);
	//设置标题自动换行
	setStyle.setWrapText(true);
	//设置内容水平靠右显示
	setContentStyle.setAlignment(HorizontalAlignment.Right);

	//标题添加单元格边框    上 下 左 右
	setStyle.setBroderTop(BorderStyle.THIN);
	setStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
	setStyle.setBroderBottom(BorderStyle.THIN);
	setStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
	setStyle.setBroderLeft(BorderStyle.THIN);
	setStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
	setStyle.setBroderRight(BorderStyle.THIN);
	setStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

	//设置单元格内容格式  (常规,数字,货币,会计专用,时间 ... ...)
	XSSFDataFormat fmt = workbook.createDataFormat();
	String format = "#,##0.00";        //货币格式,带有千位分隔符,导出后需要双击单元格才会显示
	setContentStyle.setDataFormat(fmt.getFormat(format));
    
    //创建表对象
    XSSFSheet sheet = workbook.createSheet("数据Excel表名");
    //创建标题栏(第一行),参数为行下标,从0开始
    XSSFRow titleRow1 = sheet.createRow(0);
    //在标题栏1中写入数据
    XSSFCell cell = titleRow1.createCell(0);
    cell.setCellValue("标题0");
    cell.setCellStyle(setStyle);
    //设置列宽           0列     列宽13   0.62是根据选择不同字体加不同的数字,可以先不加,运行一下看看这里设置的和运行结果相差多少,然后替换此处的0.62    256是固定的
    sheet.setColumnWidth(0,(int)((13+0.62)*256));
    cell = titleRow1.createCell(1);
    cell.setCellValue("标题1");
    cell.setCellStyle(setStyle);
    // ......
    
    //设置列宽自适应  ,27为一共几列标题,因为上面设置了列宽,这里不再使用列宽自适应
    //for(int i=0;i<27;i++){
    //    sheet.autoSizeColumn(i,true);
        //sheet.autoSizeColumn(i,"列名",getBytes().length*2*256); 中文适用
    //}
    //遍历数据
    for(int i=0;i<traccounts.size();i++){
        Traccount traccount = traccounts.get(i);
        XSSFRow dateRow = sheet.createRow(i+1);
        
        //添加数据
        XSSFCell dataCell0 = dataRow.createCell(0);
        dataCell0.setCellValue(traccount.getBatchId());
        XSSFCell dataCell1 = dataRow.createCell(1);
        dataCell1.setCellValue(traccount.getCedant());
        //   ......
    }

	//将数据写入返回流
	//创建文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
        Date date = new Date();
        String fileName = sdf.format(date)+" 系统审计日志数据.xlsx";
        log.info("导出系统审计日志数据,文件名称为:"+fileName);

        try {
            String userAgent = request.getHeader("User-Agent");
            // 针对IE或者以IE为内核的浏览器:
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        //直接导出文件到浏览器
        OutputStream os = null;
        try {
//            response.setContentType("multipart/form-data");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");

            response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", fileName));
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            os = new BufferedOutputStream(response.getOutputStream());
            workbook.write(os);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LogHandleException(10002,"导出系统审计日志数据异常");
        }finally{
            try {
                if(os != null){
                    os.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new LogHandleException(10003,"数据流关闭异常");
            }
            try {
                if(os != null){
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new LogHandleException(10003,"数据流关闭异常");
            }
        }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过以下步骤使用 EPPlus 将数据库数据导出Excel 中: 1. 连接数据库:使用 C# 中的 System.Data.SqlClient 命名空间和 SqlConnection 类连接数据库。 2. 执行 SQL 查询:使用 SqlCommand 类执行 SQL 查询,获取需要导出Excel数据。 3. 创建 Excel 文件:使用 EPPlus 创建一个新的 Excel 文件。 4. 添加工作表:使用 ExcelPackage.Workbook.Worksheets.Add() 方法添加一个新的工作表。 5. 添加表头:使用 ExcelWorksheet.Cells[row, column].Value 属性将表头添加到工作表中。 6. 将数据添加到工作表中:使用 ExcelWorksheet.Cells[row, column].Value 属性将数据添加到工作表中。 7. 保存 Excel 文件:使用 EPPlus 中的 Save() 方法将 Excel 文件保存到磁盘。 下面是示意代码: using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1"); // Add headers worksheet.Cells[1, 1].Value = "Column 1"; worksheet.Cells[1, 2].Value = "Column 2"; worksheet.Cells[1, 3].Value = "Column 3"; // Add data int row = 2; while (reader.Read()) { worksheet.Cells[row, 1].Value = reader["Column1"]; worksheet.Cells[row, 2].Value = reader["Column2"]; worksheet.Cells[row, 3].Value = reader["Column3"]; row++; } // Save Excel file package.SaveAs(new FileInfo(@"C:\Temp\MyExcelFile.xlsx")); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值