java 生成excel模板_java利用模板生成excel

public String exportCjcljd() throws IOException{

File file = new File(servletRequest.getSession().getServletContext().getRealPath("/")+ "/pages/osta/kwgl/cjcljd.xls");

ByteArrayOutputStream out=new ByteArrayOutputStream();

InputStream in = new FileInputStream(file);

HSSFWorkbook hworkbook = new HSSFWorkbook(in);// 用输入流生成poi对象,以读取excel中的内容

HSSFSheet sheet = hworkbook.getSheetAt(0);// 获取sheet

if (sheet == null) {

throw new BusinessException("文件异常!");

}

HSSFCellStyle style = hworkbook.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_LEFT);

//样式1

HSSFCellStyle style1 = hworkbook.createCellStyle();

style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);

HSSFFont font=hworkbook.createFont();

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

style1.setFont(font);

//样式2

HSSFCellStyle style2 = hworkbook.createCellStyle();

style2.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

HSSFRow row0 = sheet.getRow(0);// 获取第一行

String name=DateUtils.format(new Date(), "yyyy")+"年日常鉴定成绩处理进度记录表";

this.createCell(row0, 0, style1,HSSFCell.CELL_TYPE_STRING,name );

Calendar now = Calendar.getInstance();

String str=now.get(Calendar.YEAR)+" 年 "+(now.get(Calendar.MONTH) + 1) +" 月 "+now.get(Calendar.DAY_OF_MONTH)+" 日";

this.createCell(row0, 8, style2,HSSFCell.CELL_TYPE_STRING,str );

StringBuffer sb=new StringBuffer();

sb.append("select jh.jdjhnum,jh.createdate,(select value from tb_dic_info a where a.code=jh.kstype and a.type='JDLX') kstype ");

sb.append(",jh.zygzname,(select value from tb_dic_info a where a.code=jh.jdrank and a.type='JDDJ') jdrank,to_char(jh.jdtime,'yyyy-MM-dd') jdtime,jg.fullname ");

sb.append("from osip_osta_jdjh jh,osip_osta_jdgxtwo jt,osip_osta_jdjg jg ");

sb.append("where jh.id=jt.jdjhid and jt.jdjgid=jg.id and jh.district_code=? ");

sb.append(" and jh.validity='1' and jh.status=3 and jh.sfshtg=3 and sysdate > jh.bmjztime ");

String districtcode=(String) getSession().get(SessionConstants.WSSIP_OPERATOR_DISTRICTCODE);

List list=CommonJdbcDaoUtils.query(sb.toString(), KcbpVO.class, districtcode);

for (int i = 0; i < list.size(); i++) {

KcbpVO model=list.get(i);

HSSFRow row1 = sheet.createRow((short) (i + 3));// 建立新行 从插入数据的那一行开始

this.createCell(row1, 0, style,HSSFCell.CELL_TYPE_STRING, i+1);

if (StringUtils.isNotBlank(model.getJdjhnum()))

this.createCell(row1, 1, style,HSSFCell.CELL_TYPE_STRING, model.getJdjhnum());

if (model.getCreatedate()!=null)

this.createCell(row1, 2, style,HSSFCell.CELL_TYPE_STRING, DateUtils.format(model.getCreatedate(), "yyyy"));

if (StringUtils.isNotBlank(model.getKstype()))

this.createCell(row1, 3, style,HSSFCell.CELL_TYPE_STRING, model.getKstype());

if (StringUtils.isNotBlank(model.getZygzname()))

this.createCell(row1, 4, style,HSSFCell.CELL_TYPE_STRING, model.getZygzname());

if (StringUtils.isNotBlank(model.getJdrank()))

this.createCell(row1, 5, style,HSSFCell.CELL_TYPE_STRING, model.getJdrank());

if (model.getJdtime()!=null)

this.createCell(row1, 6, style,HSSFCell.CELL_TYPE_STRING, model.getJdtime());

if (StringUtils.isNotBlank(model.getFullname()))

this.createCell(row1,7, style,HSSFCell.CELL_TYPE_STRING, model.getFullname());

}

try {

hworkbook.write(out);

servletRequest.setAttribute("excelStream",new ByteArrayInputStream(out.toByteArray()));

servletRequest.setAttribute("filename", new String(name.getBytes("GBK"),"ISO-8859-1")+".xls");//设置文件名

return SUCCESS;

} catch (IOException e) {

e.printStackTrace();

ExceptionLogHandler.saveExceptionLog(e,(String) getSession().get(SessionConstants.WSSIP_OPERATOR_ID));

System.out.println("无法输出Excel文件");

return ERROR;

} finally{

out.close();

}

}

private void createCell(HSSFRow row, int column, HSSFCellStyle style,

int cellType, Object value) {

HSSFCell cell = row.createCell((short)column);

if (style != null) {

cell.setCellStyle(style);

}

switch (cellType) {

case HSSFCell.CELL_TYPE_BLANK: {

}

break;

case HSSFCell.CELL_TYPE_STRING: {

cell.setCellValue(value.toString());

}

break;

case HSSFCell.CELL_TYPE_NUMERIC: {

cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);

cell.setCellValue(Double.parseDouble(value.toString()));

}

break;

default:

break;

}

}

//获取输出流

public InputStream getInputExcel()

{

return (InputStream)servletRequest.getAttribute("excelStream");

}

--------------------------------------------------------

jsp页面

function exportCjcljd(){

var excelForm = document.getElementById("excelForm");

excelForm.action="${pageContext.request.contextPath}/osta/kwgl/exportCjcljd.action";

excelForm.submit();

}

069160993c335bd499ca836a227d6418.png

根据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; } }
如果您想根据Excel模板生成Java代码,可以使用一些工具来实现。其中比较常用的工具有以下几种: 1. Jxls:Jxls是一个基于POI库的Excel模板引擎,可以方便地使用Excel模板生成Excel文档。Jxls提供了丰富的语法和标签,可以实现复杂的数据填充和格式化操作。您可以使用Jxls从Excel模板中读取数据,并将数据填充到Java代码中的数据结构中,然后根据数据结构生成Java代码。 2. Apache Poi:Apache POI是一个Java处理Microsoft Office文件格式的开源库,可以读取、写入和操作Excel、Word和PowerPoint等文件。使用POI,您可以读取Excel模板中的单元格和区域,然后根据单元格和区域的位置和格式生成Java代码。需要注意的是,在使用POI生成Java代码时,需要处理Excel模板中的格式和样式,以确保生成Java代码与Excel模板的样式和格式一致。 3. EasyExcel:EasyExcel是一个基于POI的Java开源库,可以快速、简单地读取和写入Excel文件。EasyExcel提供了丰富的API和注解,可以实现复杂的数据操作和格式化。您可以使用EasyExcelExcel模板中读取数据,并将数据填充到Java代码中的数据结构中,然后根据数据结构生成Java代码。 无论您选择哪种工具,都需要先准备好Excel模板,并确定要生成Java代码的数据结构和格式。然后,您可以使用相应的工具从Excel模板中读取数据,并将数据填充到Java代码中的数据结构中,最后生成Java代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值