erp10--excel数据导出--poi

来源:互联网 发布:java 编程思想笔试题 编辑:程序博客网 时间:2024/05/08 15:30
一、97-03版本的excel    xls
HSSFWorkbook  工作簿
HSSFSheet    工作表
HSSFRow    行
HSSFCell    单元格
HSSFCellStyle    单元格样式
HSSFfont    字体

二、2007-2010版本的excel    xlsx
XSSFWorkbook  工作簿
XSSFSheet    工作表
XSSFRow    行
XSSFCell    单元格
XSSFCellStyle    单元格样式
XSSFfont    字体


其中,由HSSFWorkbook创建的对象有:
HSSFSheet、HSSFFont、HSSFCellStyle


三、demo程序
1、添加pom依赖
HSSF版本:
  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.11</version>
  5. </dependency>
XSSF:
  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi-ooxml</artifactId>
  4. <version>3.11</version>
  5. </dependency>

测试代码:
  1. package com.itcast.poi;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. import org.apache.poi.hssf.usermodel.HSSFCell;
  8. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  9. import org.apache.poi.hssf.usermodel.HSSFFont;
  10. import org.apache.poi.hssf.usermodel.HSSFRow;
  11. import org.apache.poi.hssf.usermodel.HSSFSheet;
  12. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  13. import org.apache.poi.ss.util.CellRangeAddress;
  14. publicclassTest4{
  15. staticSimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  16. publicstaticvoid main(String[] args){
  17. //创建一个excel文档,在这个excel文档中写入一句话,把excel文档输出到D盘
  18. HSSFWorkbook book =newHSSFWorkbook();//工作薄
  19. HSSFSheet sheet = book.createSheet();//工作表
  20. //设置单元格样式
  21. HSSFCellStyle cellStyle = book.createCellStyle();
  22. cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  23. cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  24. cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  25. cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  26. //水平居中对齐
  27. cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  28. //垂直居中对齐
  29. cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  30. //设置字体
  31. HSSFFont font = book.createFont();
  32. //黑体18号并且加粗
  33. font.setFontName("黑体");//字体名称
  34. font.setFontHeightInPoints((short)18);//字号大小
  35. font.setBold(true);//加粗
  36. //把字体放到样式中
  37. cellStyle.setFont(font);
  38. //15行4列
  39. for(int i =0; i <15; i++){
  40. HSSFRow row = sheet.createRow(i);
  41. /**
  42. * 设置行高
  43. */
  44. row.setHeight((short)500);
  45. for(int j =0; j <4; j++){
  46. HSSFCell cell = row.createCell(j);
  47. cell.setCellStyle(cellStyle);
  48. }
  49. }
  50. //设置列宽
  51. for(int i =0; i <4; i++){
  52. sheet.setColumnWidth(i,5000);
  53. }
  54. //合并单元格 firstRow 起始行, lastRow 截止行, firstCol 起始列, lastCol截止列
  55. sheet.addMergedRegion(newCellRangeAddress(1,1,0,3));
  56. //向合并单元格中放一个当前时间
  57. HSSFCell cell = sheet.getRow(1).getCell(0);
  58. String dateStr = sdf.format(newDate());
  59. cell.setCellValue(dateStr);
  60. //设置单元格样式
  61. HSSFCellStyle cellStyle1 = book.createCellStyle();
  62. cellStyle1.cloneStyleFrom(cellStyle);
  63. //设置字体
  64. HSSFFont font1 = book.createFont();
  65. //黑体18号并且加粗
  66. font1.setFontName("楷体");//字体名称
  67. font1.setFontHeightInPoints((short)11);//字号大小
  68. //font1.setBold(false);//加粗
  69. //把字体放到样式中
  70. cellStyle1.setFont(font1);
  71. HSSFCell contentCell = sheet.getRow(2).getCell(0);
  72. contentCell.setCellStyle(cellStyle1);
  73. contentCell.setCellValue("第一组");
  74. try{
  75. book.write(newFileOutputStream("d:\\demo3.xls"));
  76. }catch(FileNotFoundException e){
  77. // TODO Auto-generated catch block
  78. e.printStackTrace();
  79. }catch(IOException e){
  80. // TODO Auto-generated catch block
  81. e.printStackTrace();
  82. }
  83. }
  84. }

四、生成excel文件下载

摘要:
1、设置响应头
  1. response.setHeader("Content-Disposition","attachment;fileName="+newString(fileName.getBytes("utf-8"),"iso-8859-1"));
2、window.open("supplier_export.action");可以跳转
但是会打开一个新的页面,所以用download插件


1、供应商导出:
前端:

  1. iconCls:'icon-save',
  2. text:'导出',
  3. handler:function(){
  4. //alert(123);
  5. //window.open("dep.html");
  6. var formdata=$("#searchForm").serializeJSON();
  7. formdata['t1.type']=Request['type'];
  8. $.download("supplier_export.action",formdata);
  9. }


后台:
action
  1. /**
  2. * 导出--是一个excel文件
  3. * @param t1
  4. * @throws UnsupportedEncodingException
  5. */
  6. publicvoid export()throwsUnsupportedEncodingException{
  7. HttpServletResponse response =ServletActionContext.getResponse();
  8. String fileName ="供应商.xls";
  9. Supplier t1 = getT1();
  10. if(t1.getType().equals("2")){
  11. fileName="客户.xls";
  12. }
  13. response.setHeader("Content-Disposition","attachment;fileName="+newString(fileName.getBytes(),"iso-8859-1"));
  14. ServletOutputStream out;
  15. try{
  16. out = response.getOutputStream();
  17. supplierBiz.export(t1, out);
  18. }catch(IOException e){
  19. e.printStackTrace();
  20. }
  21. }

biz
  1. publicvoid export(Supplier t1 ,OutputStream out){
  2. //创建excel文档(工作薄)
  3. HSSFWorkbook book =newHSSFWorkbook();
  4. String sheetname="供应商";
  5. if(t1.getType().equals("2")){
  6. sheetname="客户";
  7. }
  8. HSSFSheet sheet = book.createSheet(sheetname);
  9. HSSFRow titleRow = sheet.createRow(0);
  10. HSSFCell cell =null;
  11. cell = titleRow.createCell(0);
  12. cell.setCellValue("名称");
  13. cell = titleRow.createCell(1);
  14. cell.setCellValue("地址");
  15. cell = titleRow.createCell(2);
  16. cell.setCellValue("联系人");
  17. cell = titleRow.createCell(3);
  18. cell.setCellValue("电话");
  19. cell = titleRow.createCell(4);
  20. cell.setCellValue("email");
  21. List<Supplier> list = supplierDao.getList(t1,null,null);
  22. int rowIndex =1;
  23. for(Supplier supplier : list){
  24. HSSFRow row = sheet.createRow(rowIndex);
  25. cell = row.createCell(0);//名称
  26. cell.setCellValue(supplier.getName());
  27. cell = row.createCell(1);//地址
  28. cell.setCellValue(supplier.getAddress());
  29. cell = row.createCell(2);//联系人
  30. cell.setCellValue(supplier.getContact());
  31. cell = row.createCell(3);//电话
  32. cell.setCellValue(supplier.getTele());
  33. cell = row.createCell(4);//email
  34. cell.setCellValue(supplier.getEmail());
  35. rowIndex++;
  36. }
  37. try{
  38. book.write(out);
  39. book.close();
  40. }catch(IOException e){
  41. // TODO Auto-generated catch block
  42. e.printStackTrace();
  43. }
  44. }

2、订单导出

前端:
$("#exportBtn").bind("click",function(){
        
        $.download("orders_export",{"id":$("#uuid").html()});
        
    })  

action:
  1. publicvoid export()throwsIOException{
  2. HttpServletResponse response =ServletActionContext.getResponse();
  3. response.setHeader("content-disposition","attachment;fileName=orders.xls");
  4. ServletOutputStream out = response.getOutputStream();
  5. String filePath=ServletActionContext.getServletContext().getRealPath(File.separator+"template"+File.separator+"orders.xls");
  6. FileInputStream in =newFileInputStream(filePath);
  7. ordersBiz.export(getId(), in, out);
  8. }

biz:
  1. publicvoid export(Long id ,InputStream in ,OutputStream out )throwsIOException{
  2. Orders orders = ordersDao.get(id);
  3. HSSFWorkbook book =newHSSFWorkbook(in);
  4. HSSFSheet sheet = book.getSheetAt(0);
  5. Supplier supplier = supplierDao.get(orders.getSupplieruuid());
  6. sheet.getRow(2).getCell(1).setCellValue(supplier.getName());
  7. sheet.getRow(2).getCell(1).setCellValue(sdf.format(orders.getCreatetime()));
  8. sheet.getRow(3).getCell(3).setCellValue(empDao.get(orders.getCreater()).getName());
  9. if(orders.getChecktime()!=null){
  10. sheet.getRow(4).getCell(1).setCellValue(sdf.format(orders.getChecktime()));
  11. sheet.getRow(5).getCell(3).setCellValue(empDao.get(orders.getChecker()).getName());
  12. }
  13. if(orders.getStarttime()!=null){
  14. sheet.getRow(5).getCell(1).setCellValue(sdf.format(orders.getStarttime()));
  15. sheet.getRow(5).getCell(3).setCellValue(empDao.get(orders.getStarter()).getName());
  16. }
  17. if(orders.getEndtime()!=null){
  18. sheet.getRow(6).getCell(1).setCellValue(sdf.format(orders.getEndtime()));
  19. sheet.getRow(6).getCell(3).setCellValue(empDao.get(orders.getEnder()).getName());
  20. }
  21. List<Orderdetail> orderdetails = orders.getOrderdetails();
  22. int rowIndex=9;
  23. HSSFCell cell =null;
  24. HSSFCellStyle cellStyle = sheet.getRow(2).getCell(0).getCellStyle();
  25. for(Orderdetail orderdetail :orderdetails){
  26. HSSFRow row = sheet.createRow(rowIndex);
  27. cell = row.createCell(0);//商品名称
  28. cell.setCellValue(orderdetail.getGoodsname());
  29. cell.setCellStyle(cellStyle);
  30. cell=row.createCell(1);//商品价格
  31. cell.setCellValue(orderdetail.getPrice());
  32. cell.setCellStyle(cellStyle);
  33. cell=row.createCell(2);//商品数量
  34. cell.setCellValue(orderdetail.getNum());
  35. cell.setCellStyle(cellStyle);
  36. cell=row.createCell(3);//金额
  37. cell.setCellValue(orderdetail.getMoney());
  38. cell.setCellStyle(cellStyle);
  39. rowIndex++;
  40. }
  41. book.write(out);
  42. }


POI模板导出

 

如果在工作中导出的单元格非常复杂时,设置样式、字体、合并单元格等代码量比较大,所以这时我们可以把即将导出的表格提前把样式、字体等都设置好,直接当做导出模板应用就可以了。

 

1、 提前做好excel模板,放到项目中

 

2、 模板拷贝到项目中

 

 

3、 BIZ中的了逻辑实现

/**

 * 订单的导出

 * @param in

 * @param out

 * @param id

 * @throws IOException

 */

public void export(InputStream in,OutputStream out,Long idthrows IOException{

//现在的工作薄对象就是项目中的那份模板文件,所有样式都已存在,直接用就可以

HSSFWorkbook book = new HSSFWorkbook(in);

HSSFSheet sheet = book.getSheetAt(0);

Orders orders = ordersDao.get(id);

 /**

  * 以下就是找到相应数据所对应的单元格位置 赋值即可

  */

//供应商

sheet.getRow(2).getCell(1).setCellValue(supplierDao.get(orders.getSupplieruuid()).getName());

//下单时间

String createtime =  orders.getCreatetime()==null?"":sdf.format(orders.getCreatetime());

sheet.getRow(3).getCell(1).setCellValue(createtime);

//审核时间

String checktime =  orders.getChecktime()==null?"":sdf.format(orders.getChecktime());

sheet.getRow(4).getCell(1).setCellValue(checktime);

//确认时间

String starttime =  orders.getStarttime()==null?"":sdf.format(orders.getStarttime());

sheet.getRow(5).getCell(1).setCellValue(starttime);

//入库时间

String endtime =  orders.getEndtime()==null?"":sdf.format(orders.getEndtime());

sheet.getRow(6).getCell(1).setCellValue(endtime);

//下单员

if(orders.getCreater()!=null){

sheet.getRow(3).getCell(3).setCellValue(empDao.get(orders.getCreater()).getName());

}

//审核员

if(orders.getChecker()!=null){

sheet.getRow(4).getCell(3).setCellValue(empDao.get(orders.getChecker()).getName());

}

//确认人

if(orders.getStarter()!=null){

sheet.getRow(5).getCell(3).setCellValue(empDao.get(orders.getStarter()).getName());

}

//库管员

if(orders.getEnder()!=null){

sheet.getRow(6).getCell(3).setCellValue(empDao.get(orders.getEnder()).getName());

}

//商品名称价格数量金额

List<Orderdetail> orderdetails = orders.getOrderdetails();

//取现有的样式(因为订单项所在的表格没有样式,可以从其他位置复制一份样式过来)

HSSFCellStyle cellStyle = sheet.getRow(8).getCell(0).getCellStyle();

int rownum=9; //从模板中能看出来 起始行是9

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

HSSFRow createRow = sheet.createRow(rownum+i);

createRow.createCell(0).setCellStyle(cellStyle); // 设置复制过来的样式

createRow.getCell(0).setCellValue(orderdetails.get(i).getGoodsname());

createRow.createCell(1).setCellStyle(cellStyle);

createRow.getCell(1).setCellValue(orderdetails.get(i).getPrice());

createRow.createCell(2).setCellStyle(cellStyle);

createRow.getCell(2).setCellValue(orderdetails.get(i).getNum());

createRow.createCell(3).setCellStyle(cellStyle);

createRow.getCell(3).setCellValue(orderdetails.get(i).getMoney());

}

book.write(out);

book.close();

}

4、 action中获取模板文件

/**

 * 订单信息导出

 * @throws IOException

 */

public void export() throws IOException{

//从项目中获取模板所在路径                                          File.separator 在window系统下:\  linux系统下:  /

String filepath=ServletActionContext.getServletContext().getRealPath(File.separator)

+"template"+File.separator+"orders.xls";

HttpServletResponse response = ServletActionContext.getResponse();

//设置头部信息

response.setHeader("Content-Disposition""attachment;fileName=orders.xls");

ServletOutputStream out = response.getOutputStream();

ordersBiz.export(new FileInputStream(filepath), out, getId());

}

 




四、供应商及客户数据导入

前端:
  1. //导入
  2. $('#importBtn').bind('click',function(){
  3. $.ajax({
  4. url:'supplier_doImport.action',
  5. type:'post',
  6. data:newFormData($("#importForm")[0]),
  7. dataType:'json',
  8. processData:false,
  9. contentType:false,
  10. success:function(data){
  11. if(data.success){
  12. $("#importWindow").window('close');
  13. $("#grid").datagrid("reload");
  14. }
  15. $.messager.alert('提示',data.message);
  16. }
  17. })
  18. });

后台:
action:
  1. privateFile file;
  2. privateString fileFileName;
  3. privateString fileContentType;
  4. //set\get方法在上面
  5. publicvoid doImport(){
  6. //获取上传的文件 file
  7. try{
  8. FileInputStream in =newFileInputStream(file);
  9. supplierBiz.doImport(in);
  10. write(ajaxReturn(true,"导入成功"));
  11. }catch(Exception e){
  12. write(ajaxReturn(false,"导入失败"));
  13. e.printStackTrace();
  14. }
  15. 0
  16. }

biz:
  1. /**
  2. * 导入
  3. * @param in
  4. * @throws IOException
  5. */
  6. publicvoid doImport(FileInputStream in)throwsIOException{
  7. HSSFWorkbook book =newHSSFWorkbook(in);
  8. HSSFSheet sheet = book.getSheetAt(0);
  9. String sheetName = sheet.getSheetName();
  10. String type="1";
  11. if(sheetName.equals("客户")){
  12. type="2";
  13. }
  14. int lastRowNum = sheet.getLastRowNum();
  15. for(int i =1; i <= lastRowNum; i++){
  16. Supplier supplier =newSupplier();
  17. HSSFRow row = sheet.getRow(i);
  18. String name = row.getCell(0).getStringCellValue();
  19. supplier.setName(name);
  20. List<Supplier> list = supplierDao.getList(supplier,null,null);
  21. if(list!=null&&list.size()>0){
  22. supplier = list.get(0);
  23. }
  24. String address = row.getCell(1).getStringCellValue();
  25. supplier.setAddress(address);
  26. String contact = row.getCell(2).getStringCellValue();
  27. supplier.setContact(contact);
  28. String tele = row.getCell(3).getStringCellValue();
  29. supplier.setTele(tele);
  30. String email = row.getCell(4).getStringCellValue();
  31. supplier.setEmail(email);
  32. supplier.setType(type);
  33. if(list==null||list.size()==0){//判断是否通过name找到数据,如果没有找到数据,需要保存,如果找到数据的不需要执行add方法
  34. supplierDao.add(supplier);
  35. }
  36. }
  37. }






































原创粉丝点击