java 根据excel模板格式导出指定格式的excel

@Component
public class ExcelUtils {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private SysUserMapper sysUserMapper;

    //声明一个该工具类的静态的内部对象
    private static ExcelUtils excelUtils;

    //工具类中需要注入service,dao等需要
    //使用注解@PostConstruct把需要使用的service,dao等加载到上面定义的静态内部对象中
    @PostConstruct
    public void init() {
        excelUtils = this;
        excelUtils.sysUserMapper =  this.sysUserMapper;
    }

    /**
     *tempPath 模板文件路径
     *path 文件路径
     *list 集合数据
     */
    public void exportExcel(String tempPath, String path, HttpServletResponse response, List<OrderVO> list) {
        File newFile = createNewFile(tempPath, path);
        InputStream is = null;
        XSSFWorkbook workbook = null;
        XSSFSheet sheet = null;
        try {
            is = new FileInputStream(newFile);// 将excel文件转为输入流
            workbook = new XSSFWorkbook(is);// 创建个workbook,
            // 获取第一个sheet
            sheet = workbook.getSheetAt(0);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        if (sheet != null) {
            try {
                // 写数据
                FileOutputStream fos = new FileOutputStream(newFile);
                XSSFRow row = sheet.getRow(0);
                if (row == null) {
                    row = sheet.createRow(0);
                }
                XSSFCell cell = row.getCell(0);
                if (cell == null) {
                    cell = row.createCell(0);
                }
                cell.setCellValue("我是标题");

                for (int i = 0; i < list.size(); i++) {
                    OrderVO vo = list.get(i);
                    row = sheet.createRow(i+2); //从第三行开始

                    //这里就可以使用sysUserMapper,做相应的操作
                    //User user = excelUtils.sysUserMapper.selectByPrimaryKey(vo.getId());                  

                    //根据excel模板格式写入数据....
                    createRowAndCell(vo.getTaobaoOrderId(), row, cell, 0);
                    createRowAndCell(vo.getOrderInfo(), row, cell, 1);
                    createRowAndCell(vo.getLy(), row, cell, 2);
                    createRowAndCell(format.format(DateFormat.getDateInstance().parse(vo.getCreateTime())), row, cell, 3);
                    createRowAndCell(vo.getTotal(), row, cell, 4);
                    createRowAndCell(getOrderSource(vo.getSourceId()), row, cell, 5);
                    //.....
                }
                workbook.write(fos);
                fos.flush();
                fos.close();

                // 下载
                InputStream fis = new BufferedInputStream(new FileInputStream(
                        newFile));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                response.reset();
                response.setContentType("text/html;charset=UTF-8");
                OutputStream toClient = new BufferedOutputStream(
                        response.getOutputStream());
                response.setContentType("application/x-msdownload");
                String newName = URLEncoder.encode(
                        "订单" + System.currentTimeMillis() + ".xlsx",
                        "UTF-8");
                response.addHeader("Content-Disposition",
                        "attachment;filename=\"" + newName + "\"");
                response.addHeader("Content-Length", "" + newFile.length());
                toClient.write(buffer);
                toClient.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 删除创建的新文件
        this.deleteFile(newFile);
    }

    /**
     *根据当前row行,来创建index标记的列数,并赋值数据
     */
    private void createRowAndCell(Object obj, XSSFRow row, XSSFCell cell, int index) {
        cell = row.getCell(index);
        if (cell == null) {
            cell = row.createCell(index);
        }

        if (obj != null)
            cell.setCellValue(obj.toString());
        else 
            cell.setCellValue("");
    }

    /**
     * 复制文件
     * 
     * @param s
     *            源文件
     * @param t
     *            复制到的新文件
     */

    public void fileChannelCopy(File s, File t) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(s), 1024);
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取excel模板,并复制到新文件中供写入和下载
     * 
     * @return
     */
    public File createNewFile(String tempPath, String rPath) {
        // 读取模板,并赋值到新文件************************************************************
        // 文件模板路径
        String path = (tempPath);
        File file = new File(path);
        // 保存文件的路径
        String realPath = rPath;
        // 新的文件名
        String newFileName = System.currentTimeMillis() + ".xlsx";
        // 判断路径是否存在
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 写入到新的excel
        File newFile = new File(realPath, newFileName);
        try {
            newFile.createNewFile();
            // 复制模板到新文件
            fileChannelCopy(file, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFile;
    }

    /**
     * 下载成功后删除
     * 
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}



@Controller
@RequestMapping(value = "/export")
public class ExcelController {

    @RequestMapping(value = "/list")
    @ResponseBody
    public void excel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String tempPath = request.getSession().getServletContext().getRealPath("/") + "template/" + "order.xlsx";
        String path = request.getSession().getServletContext().getRealPath("/") + "template/";

        Map<String, Object> map = new HashMap<String, Object>();
        if (..) {
            //查询数据的条件
            map.put();
        }
        List<OrderVO> list = orderMapper.selectOrderByExcel(map);
        ExcelUtils ex = new ExcelUtils();
        ex.exportExcel(tempPath, path, response, list);
    }
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
根据excel模板动态导出数据库数据 package text; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletContext; import net.sf.jxls.transformer.XLSTransformer; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class TextAction extends ActionSupport { /** */ private static final long serialVersionUID = 1L; private String filename; @SuppressWarnings("rawtypes") public String export() throws Exception { String templateFile = "18.xls"; // String sql = "select * from t_ry order by rybm"; // exportAndDownload(templateFile, DataBase.retrieve(sql)); List datas = new ArrayList(); @SuppressWarnings("unchecked") HashMap map = new HashMap(); map.put("name", "1111"); datas.add(map); exportAndDownload(templateFile, datas); return SUCCESS; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void exportAndDownload(String templateFile, List datas) { try { filename = UUID.randomUUID() + templateFile; // FacesContext context = FacesContext.getCurrentInstance(); // ServletContext servletContext = (ServletContext) // context.getExternalContext().getContext(); ServletContext servletContext = ServletActionContext .getServletContext(); String path = servletContext.getRealPath("\\ExcelFile"); String srcFilePath = path + "\\template\\" + templateFile; String destFilePath = path + "\\download\\" + filename; Map beanParams = new HashMap(); beanParams.put("results", datas); XLSTransformer transfer = new XLSTransformer(); transfer.transformXLS(srcFilePath, beanParams, destFilePath); // Browser.execClientScript("window.location.href='../ExcelFile/downloadfile.jsp?filename=" // + destFile + "';"); } catch (Exception e) { e.printStackTrace(); } } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值