前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java导出excel的两种方式

java导出excel的两种方式

作者头像
jiankang666
发布2022-05-12 20:56:42
2.5K0
发布2022-05-12 20:56:42
举报
文章被收录于专栏:java基础笔记

这篇在我的csdn上阅读数近三万,点赞几十个,算是比较火的一篇了,在这里分享一下,公司总免不了与文件导入导出打交道,前段时间我做了媒体预览服务,媒体打包服务,最近又在做大文件拆分服务,以后会分享其他相关的,没时间读,可以先收藏。

一、在后台实现,利用java的poi

1、导入jar包,需要导入lib文件夹下如下包:

代码语言:javascript
复制
poi-3.11-20141221.jar
poi-ooxml.jar
poi-ooxml-schemas.jar

2、在util下写一个公共类,该类主要利用Jakarta POI HSSF API组件(用于操作Excel的组件),主要部分包括Excel对象,样式和格式,还有辅助操作。

代码语言:javascript
复制
常用组件:
    HSSFWorkbook        excel的文档对象
    HSSFSheet           excel的表单
    HSSFRow             excel的行
    HSSFCell            excel的格子单元
    HSSFFont            excel字体
    HSSFDataFormat      日期格式
    HSSFHeader         sheet头
    HSSFFooter         sheet尾(只有打印的时候才能看到效果)


样式:
    HSSFCellStyle                       cell样式
    辅助操作包括:
    HSSFDateUtil                        日期
    HSSFPrintSetup                      打印
    HSSFErrorConstants                  错误信息表

3、该类的操作代码如下:

代码语言:javascript
复制
package com.bdqn.util;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

public class ExportExcel {

  // 显示的导出表的标题
  private String title;
  // 导出表的列名
  private String[] rowName;
  private List<Object[]> dataList = new ArrayList<Object[]>();

  // 构造函数,传入要导出的数据
  public ExportExcel(String title, String[] rowName, List<Object[]> dataList) {
    this.dataList = dataList;
    this.rowName = rowName;
    this.title = title;
  }

  // 导出数据
  public void export(OutputStream out) throws Exception {
    try {
      HSSFWorkbook workbook = new HSSFWorkbook();
      HSSFSheet sheet = workbook.createSheet(title);

      // 产生表格标题行
      HSSFRow rowm = sheet.createRow(0);
      HSSFCell cellTitle = rowm.createCell(0);


      //sheet样式定义【】
      HSSFCellStyle columnTopStyle=this.getColumnTopStyle(workbook);
      HSSFCellStyle style=this.getStyle(workbook);
      sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
      cellTitle.setCellStyle(columnTopStyle);
      cellTitle.setCellValue(title);

      // 定义所需列数
      int columnNum = rowName.length;
      HSSFRow rowRowName = sheet.createRow(2);

      // 将列头设置到sheet的单元格中
      for (int n = 0; n < columnNum; n++) {
        HSSFCell cellRowName = rowRowName.createCell(n);
        cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);
        HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
        cellRowName.setCellValue(text);
        cellRowName.setCellStyle(columnTopStyle);

      }
      // 将查询到的数据设置到sheet对应的单元格中
      for (int i = 0; i < dataList.size(); i++) {
        Object[] obj = dataList.get(i);// 遍历每个对象
        HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数

        for (int j = 0; j < obj.length; j++) {
          HSSFCell cell = null;
          if (j == 0) {
            cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
            cell.setCellValue(i + 1);
          } else {
            cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
            if (!"".equals(obj[j]) && obj[j] != null) {
              cell.setCellValue(obj[j].toString());
            }
          }
          cell.setCellStyle(style);

        }

      }

      // 让列宽随着导出的列长自动适应
      for (int colNum = 0; colNum < columnNum; colNum++) {
        int columnWidth = sheet.getColumnWidth(colNum) / 256;
        for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
          HSSFRow currentRow;
          if (sheet.getRow(rowNum) == null) {
            currentRow = sheet.createRow(rowNum);
          } else {
            currentRow = sheet.getRow(rowNum);
          }
          if (currentRow.getCell(colNum) != null) {
            HSSFCell currentCell = currentRow.getCell(colNum);
            if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
              int length = currentCell.getStringCellValue().getBytes().length;
              if (columnWidth < length) {
                columnWidth = length;
              }
            }
          }
        }
        if (colNum == 0) {
          sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
        } else {
          sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
        }
      }

      if (workbook != null) {
        try {

          workbook.write(out);

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    } catch (Exception e) {

    }
  }

4、单元格样式:

代码语言:javascript
复制
/*
   * 列头单元格样式
   */
  public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
    // 设置字体
    HSSFFont font = workbook.createFont();

    // 设置字体大小
    font.setFontHeightInPoints((short) 11);
    // 字体加粗
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    // 设置字体名字
    font.setFontName("Courier New");
    // 设置样式
    HSSFCellStyle style = workbook.createCellStyle();
    // 设置低边框
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    // 设置低边框颜色
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    // 设置右边框
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    // 设置顶边框
    style.setTopBorderColor(HSSFColor.BLACK.index);
    // 设置顶边框颜色
    style.setTopBorderColor(HSSFColor.BLACK.index);
    // 在样式中应用设置的字体
    style.setFont(font);
    // 设置自动换行
    style.setWrapText(false);
    // 设置水平对齐的样式为居中对齐;
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    return style;

  }

  public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
    // 设置字体
    HSSFFont font = workbook.createFont();
    // 设置字体大小
    font.setFontHeightInPoints((short) 10);
    // 字体加粗
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    // 设置字体名字
    font.setFontName("Courier New");
    // 设置样式;
    HSSFCellStyle style = workbook.createCellStyle();
    // 设置底边框;
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    // 设置底边框颜色;
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    // 设置左边框;
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    // 设置左边框颜色;
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    // 设置右边框;
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    // 设置右边框颜色;
    style.setRightBorderColor(HSSFColor.BLACK.index);
    // 设置顶边框;
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    // 设置顶边框颜色;
    style.setTopBorderColor(HSSFColor.BLACK.index);
    // 在样式用应用设置的字体;
    style.setFont(font);
    // 设置自动换行;
    style.setWrapText(false);
    // 设置水平对齐的样式为居中对齐;
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    // 设置垂直对齐的样式为居中对齐;
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    return style;
  }

5、前台主要代码如下:

5.1 第一种,我们没有传入页面的查询参数,到后台我们无论怎么查询,都是把整个数据库不分条件的全部导出。不能够满足用户需求,体验不好,不推荐。

代码语言:javascript
复制
  <button type="button" class="btn btn-success" id="delPro" onclick="dao()">导出Excel</button>
function dao() {
  location.href="MedicineAdminServlet?a=dao&pageon="+${page.pageon};
}

5、2第二种,我们往后台传入时,把查询的参数一并传入后台,后台接收后作为条件去数据库找符合条件的,查到符合条件的导出,比较人性化。

代码语言:javascript
复制
<a href="SendMedicineServlet?a=dao&patientid=${param.patientid }&prescriptionid=${param.prescriptionid}&patientname=${param.patientname }&starttime=${param.starttime }&endtime=${param.endtime }">
          <button type="button" class="btn btn-success" id="delPro">导出Excel</button>
          </a>

6、为了方便读者理解,前端页面如下:查询条件为病历号,姓名等,会根据曾经的查询条件导出。

7、后台servlet操作主要代码如下:(传入当前页将会只打印当前页)

(1)这里主要对标题命名,列头命名,获取数据库中的信息装进list里

代码语言:javascript
复制
/**
     * 导出excel文件
     */

    else if (a.equals("dao")) {
      String patientid = request.getParameter("patientid");
      int patientid3 = 0;
      if (patientid != null && !patientid.equals("")) {
        patientid3 = Integer.parseInt(patientid);
      }

      String dname = request.getParameter("dname");
      String subjectroom = request.getParameter("subjectroom");
      String starttime = request.getParameter("starttime");
      String endtime = request.getParameter("endtime");

      // 页码
      int pageon = 1;
      String pageon1 = request.getParameter("pageon");
      if (pageon1 != null && !pageon1.equals("")) {
        pageon = Integer.parseInt(pageon1);
      }
      // 操作导出excel
      List<RegRum> selectlists = rs.querySelect2(patientid3, dname, subjectroom, starttime, endtime);
     //excel标题
      String title = "挂号信息表";
      //excel列头信息
      String[] rowsName = new String[] { "门诊编号", "主治医师", "挂号时间", "挂号科室", "状态" };
      List<Object[]> dataList = new ArrayList<Object[]>();
      Object[] objs = null;
      for (int i = 0; i < selectlists.size(); i++) {
        RegRum regRum = selectlists.get(i);
        objs = new Object[rowsName.length];
        objs[0] = regRum.getPatientid();
        objs[1] = regRum.getDoctor().getDname();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objs[2] = regRum.getDate();
        objs[3] = regRum.getDoctor().getSubroomname();
        objs[4] = regRum.getStatus();
        dataList.add(objs);

      }

8、下面这部分代码主要是把数据传给浏览器,前面部分告诉浏览器该数据流是什么类型的,本例传的是excel格式的,浏览器会自动判定为excel,提示是否保存。

代码语言:javascript
复制
//给文件命名。随机命名
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
     //告诉浏览器数据格式,将头和数据传到前台
      String headStr = "attachment; filename=\"" + fileName + "\"";
      response.setContentType("APPLICATION/OCTET-STREAM");
      response.setHeader("Content-Disposition", headStr);
      OutputStream out = response.getOutputStream();

//调用poi的工具类
      ExportExcel ex = new ExportExcel(title, rowsName, dataList);
      try {
        ex.export(out);
      } catch (Exception e) {
        e.printStackTrace();
      }
      out.flush();
      out.close();
      return;
    }

9、注意:

(1)如果从数据库查到的是数字,比如0代表男,1代表女,不加处理,会导出数字,

(2)处理方法如下:(主要代码与第七点差不多),大致思路就是在往list集合中添加每一行数据时,对需要改动的在add进入list之前赋需要的值。(跟上面对比一下就能明白)

(3)这段代码最后几行可以看出来如何操作库里数据与前端想要展示不一致的思路。前面这么一堆在这儿,主要是前台传过来的字段,用来组装sql查询需要的数据,我这边是通过param参数传递的,前台传的如何是json格式的,与这个类似,获取组装即可。

代码语言:javascript
复制
String patientid1 = request.getParameter("patientid");
      int patientid = 0;
if (patientid1 != null && !patientid1.equals("")) {
        patientid = Integer.parseInt(patientid1);
      }
String prescriptionid1 = request.getParameter("prescriptionid");
      int prescriptionid = 0;
if (prescriptionid1 != null && !prescriptionid1.equals("")) {
        prescriptionid = Integer.parseInt(prescriptionid1);
      }
String patientname = request.getParameter("patientname");
String starttime = request.getParameter("starttime");
String endtime = request.getParameter("endtime");
      List<Prescription> prescriptions = new ArrayList<Prescription>();
      prescriptions = sm.queryDao(prescriptionid, patientid, patientname, starttime, endtime);
String title = "发药信息表";
String[] rowsName = new String[] { "处方号", "病历号", "姓名", "日期", "状态" };
      List<Object[]> dataList = new ArrayList<Object[]>();
//导出excel
Object[] objs = null;
for (int i = 0; i < prescriptions.size(); i++) {
        Prescription regRum = prescriptions.get(i);
        objs = new Object[rowsName.length];
        objs[0] = regRum.getPrescriptionid();
        objs[1] = regRum.getPatientid();
        objs[2] = regRum.getName();
        objs[3] = regRum.getPrescriptiondate();
        //对数字的操作
if(regRum.getStatus().equals("1")) {
          objs[4] = "已结算";
        }
else {
          objs[4]="已发药";
        }
        dataList.add(objs);
      }

10.数据库操作代码如下:

(1)比较简单,只是把满足条件的list集合传到servlet,转变为集合,方便poi类调用。

(2)代码是用jndi连接池去数据库查的,其他形式的自行实现即可,不过看这篇文章,肯定数据都有了,主要就是参考excel如何导出的,可以忽略。

代码语言:javascript
复制
@Override
public List<Prescription> query(int prescriptionid,int patientid, String patientname, String starttime, String endtime, int pageon) {
    Connection con = Jndi.getConnection();
    ResultSet rs = null;
    PreparedStatement ps = null;
    String sql = "select p.patientid,p.prescriptionid,r.patientname, p.diagnose ,p.prescriptiondate,sum(chargemoney*number),p.`pstatus` \r\n"
        + "from prescription p,regnum r,chargeitem c,prescriptioncharge pc  \r\n" + "\r\n"
        + " where  p.patientid=r.patientid and pc.prescriptionid=p.prescriptionid\r\n" + "\r\n" + "\r\n"
        + " and c.chargeid=pc.chargeid   ";
if (patientid != 0) {
      sql = sql + " and p.patientid=" + patientid;
    }
if (prescriptionid != 0) {
      sql = sql + " and p.prescriptionid=" + prescriptionid;
    }
if (patientname != null && !patientname.equals("")) {
      sql = sql + " and r.patientname like '%" + patientname + "%'";
    }
if (starttime != null && !starttime.equals("")) {
      sql = sql + " and p.prescriptiondate>'" + starttime + "'";
    }
if (endtime != null && !endtime.equals("")) {
      sql = sql + " and p.prescriptiondate<'" + endtime + "'";
    }


    sql = sql + "  GROUP BY p.prescriptionid";
if (pageon != 0) {
      sql = sql + " limit " + (pageon - 1) * 4 + ",4";
    }

    List<Prescription> listregs = new ArrayList<Prescription>();
try {
      ps = con.prepareStatement(sql);
      rs = ps.executeQuery();

while (rs.next()) {
        Prescription prescription = new Prescription();
        prescription.setPatientid(rs.getInt("patientid"));
        prescription.setPrescriptionid(rs.getInt("p.prescriptionid"));
        prescription.setDiagnose(rs.getString("diagnose"));
        prescription.setPrescriptiondate(rs.getString("prescriptiondate"));
        prescription.setStatus(rs.getString("pstatus"));
        prescription.setSummoney(rs.getDouble(6));
        prescription.setName(rs.getString(3));
        listregs.add(prescription);
      }

    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      Jndi.close(rs, ps, con);
    }
    return listregs;

以上就是第一种方式,比较复杂,如果想很快搞定,可以用纯js在前端导出table表格,需要导入四个js文件。引入进去。

二、纯js实现前台导出excel

1、导入js文件,可能也需要导入jquery文件,自行尝试。所需js文件地址。

链接:https://pan.baidu.com/s/14-riXUTElxWaLHRHLe04SA 提取码:fpnp

代码语言:javascript
复制
<script type="text/javascript" src="<%=path %>/Js/jszip.min.js"></script>
<script type="text/javascript" src="<%=path %>/Js/demo.page.js"></script>
<script type="text/javascript" src="<%=path %>/Js/excel-gen.js"></script>
<script type="text/javascript" src="<%=path %>/Js/FileSaver.js"></script>

2、js代码如下:

代码语言:javascript
复制
<script type="text/javascript">
  $(document).ready(function(){
    alert()
    excel = new ExcelGen({
      "src_id":"test_table",//table的id
"show_header":true
    });
    $("#generate-excel").click(function () {
      excel.generate();//执行导入包中的方法。
    })
  });
</script>

3、body中主要代码:

代码语言:javascript
复制
<table class="table table-bordered table-hover definewidth m10" id="test_table">
//id在table中写
//调用方法名在button写
<button type="button" class="btn btn-success" id="generate-excel">导出Excel</button>

注意:第二种方式,只能导出当前页的信息,它是根据table里面tr的数量导的,不会打印下一页。如果希望打印下一页的内容,提供一种思路,可以在按钮上添加跳转页面,跳到另一个页面,让另一个页面返回数据库全查需要的数据,写入新建页的table中,打印新table,有兴趣的可以尝试。到这儿,可能读累了吧,听懂的给个赞,thanks.

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-02-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 java基础笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档