将数据导出到Excel(java操作Excel)

来源:互联网 发布:win7如何设置网络类型 编辑:程序博客网 时间:2024/05/01 13:52

1.封装要到处的数据类,这里使用Student类举例:

[java] view plaincopyprint?
  1. package com.jeelon.exportExcle;  
  2.   
  3. public class Student {  
  4.     private int id;  
  5.     private String name ;  
  6.     private int age;  
  7.     private String address;  
  8.     private String tel;  
  9.     private char sex;  
  10.     public int getId() {  
  11.         return id;  
  12.     }  
  13.     public void setId(int id) {  
  14.         this.id = id;  
  15.     }  
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.     public void setName(String name) {  
  20.         this.name = name;  
  21.     }  
  22.     public int getAge() {  
  23.         return age;  
  24.     }  
  25.     public void setAge(int age) {  
  26.         this.age = age;  
  27.     }  
  28.     public String getAddress() {  
  29.         return address;  
  30.     }  
  31.     public void setAddress(String address) {  
  32.         this.address = address;  
  33.     }  
  34.     public String getTel() {  
  35.         return tel;  
  36.     }  
  37.     public void setTel(String tel) {  
  38.         this.tel = tel;  
  39.     }  
  40.     public char getSex() {  
  41.         return sex;  
  42.     }  
  43.     public void setSex(char sex) {  
  44.         this.sex = sex;  
  45.     }  
  46.     @Override  
  47.     public String toString() {  
  48.         return "Student [id=" + id + ", name=" + name + ", age=" + age  
  49.                 + ", address=" + address + ", tel=" + tel + ", sex=" + sex  
  50.                 + "]";  
  51.     }  
  52.     public Student(int id, String name, int age, String address, String tel,  
  53.             char sex) {  
  54.         super();  
  55.         this.id = id;  
  56.         this.name = name;  
  57.         this.age = age;  
  58.         this.address = address;  
  59.         this.tel = tel;  
  60.         this.sex = sex;  
  61.     }  
  62.     public Student() {  
  63.         super();  
  64.     }  
  65.       
  66.       
  67. }  


 

2.ExportExcel工具类

[java] view plaincopyprint?
  1. package com.jeelon.exportExcle;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import org.apache.poi.hssf.usermodel.HSSFCell;  
  9. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  10. import org.apache.poi.hssf.usermodel.HSSFFont;  
  11. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  12. import org.apache.poi.hssf.usermodel.HSSFRow;  
  13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  15. import org.apache.poi.hssf.util.HSSFColor;  
  16. import org.apache.poi.hssf.util.Region;  
  17.   
  18. /** 
  19.  * EXCEL报表工具类. 
  20.  *  
  21.  * @author Jeelon 
  22.  */  
  23. public class ExportExcel {  
  24.   
  25.     private HSSFWorkbook wb = null;  
  26.     private HSSFSheet sheet = null;  
  27.   
  28.     /** 
  29.      * @param wb 
  30.      * @param sheet  
  31.      */  
  32.     public ExportExcel(HSSFWorkbook wb, HSSFSheet sheet) {  
  33.         // super();  
  34.         this.wb = wb;  
  35.         this.sheet = sheet;  
  36.     }  
  37.   
  38.     /** 
  39.      * 创建通用EXCEL头部 
  40.      *  
  41.      * @param headString 
  42.      *            头部显示的字符 
  43.      * @param colSum 
  44.      *            该报表的列数 
  45.      */  
  46.     @SuppressWarnings({ "deprecation""unused" })  
  47.     public void createNormalHead(String headString, int colSum) {  
  48.         HSSFRow row = sheet.createRow(0);  
  49.         // 设置第一行  
  50.         HSSFCell cell = row.createCell(0);  
  51.         // row.setHeight((short) 1000);  
  52.   
  53.         // 定义单元格为字符串类型  
  54.         cell.setCellType(HSSFCell.ENCODING_UTF_16);// 中文处理  
  55.         cell.setCellValue(new HSSFRichTextString(headString));  
  56.   
  57.         // 指定合并区域  
  58.         /** 
  59.          * public Region(int rowFrom, short colFrom, int rowTo, short colTo) 
  60.          */  
  61.         sheet.addMergedRegion(new Region(0, (short00, (short) colSum));  
  62.   
  63.         // 定义单元格格式,添加单元格表样式,并添加到工作簿  
  64.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  65.         // 设置单元格水平对齐类型  
  66.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐  
  67.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐  
  68.         cellStyle.setWrapText(true);// 指定单元格自动换行  
  69.   
  70.         // 设置单元格字体  
  71.         HSSFFont font = wb.createFont();  
  72.         // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  73.         // font.setFontName("宋体");  
  74.         // font.setFontHeight((short) 600);  
  75.         // cellStyle.setFont(font);  
  76.         cell.setCellStyle(cellStyle);  
  77.     }  
  78.   
  79.     /** 
  80.      * 创建通用报表第二行 
  81.      *  
  82.      * @param params 
  83.      *            统计条件数组 
  84.      * @param colSum 
  85.      *            需要合并到的列索引 
  86.      */  
  87.     @SuppressWarnings("deprecation")  
  88.     public void createNormalTwoRow(String[] params, int colSum) {  
  89.         // 创建第二行  
  90.         HSSFRow row1 = sheet.createRow(1);  
  91.   
  92.         row1.setHeight((short400);  
  93.   
  94.         HSSFCell cell2 = row1.createCell(0);  
  95.   
  96.         cell2.setCellType(HSSFCell.ENCODING_UTF_16);  
  97.         cell2.setCellValue(new HSSFRichTextString("时间:" + params[0] + "至"  
  98.                 + params[1]));  
  99.   
  100.         // 指定合并区域  
  101.         /** 
  102.          * public Region(int rowFrom, short colFrom, int rowTo, short colTo) 
  103.          */  
  104.         sheet.addMergedRegion(new Region(1, (short01, (short) colSum));  
  105.   
  106.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  107.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐  
  108.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐  
  109.         cellStyle.setWrapText(true);// 指定单元格自动换行  
  110.   
  111.         // 设置单元格字体  
  112.         HSSFFont font = wb.createFont();  
  113.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  114.         font.setFontName("宋体");  
  115.         font.setFontHeight((short250);  
  116.         cellStyle.setFont(font);  
  117.   
  118.         cell2.setCellStyle(cellStyle);  
  119.     }  
  120.   
  121.     /** 
  122.      * 设置报表标题 
  123.      *  
  124.      * @param columHeader 
  125.      *            标题字符串数组 
  126.      */  
  127.     public void createColumHeader(String[] columHeader) {  
  128.   
  129.         // 设置列头 在第三行  
  130.         HSSFRow row2 = sheet.createRow(2);  
  131.   
  132.         // 指定行高  
  133.         row2.setHeight((short600);  
  134.   
  135.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  136.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐  
  137.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐  
  138.         cellStyle.setWrapText(true);// 指定单元格自动换行  
  139.   
  140.         // 单元格字体  
  141.         HSSFFont font = wb.createFont();  
  142.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  143.         font.setFontName("宋体");  
  144.         font.setFontHeight((short250);  
  145.         cellStyle.setFont(font);  
  146.   
  147.         // 设置单元格背景色  
  148.         cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);  
  149.         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  150.   
  151.         HSSFCell cell3 = null;  
  152.   
  153.         for (int i = 0; i < columHeader.length; i++) {  
  154.             cell3 = row2.createCell(i);  
  155.             cell3.setCellType(HSSFCell.ENCODING_UTF_16);  
  156.             cell3.setCellStyle(cellStyle);  
  157.             cell3.setCellValue(new HSSFRichTextString(columHeader[i]));  
  158.         }  
  159.     }  
  160.   
  161.     /** 
  162.      * 创建内容单元格 
  163.      *  
  164.      * @param wb 
  165.      *            HSSFWorkbook 
  166.      * @param row 
  167.      *            HSSFRow 
  168.      * @param col 
  169.      *            short型的列索引 
  170.      * @param align 
  171.      *            对齐方式 
  172.      * @param val 
  173.      *            列值 
  174.      */  
  175.     public void cteateCell(HSSFWorkbook wb, HSSFRow row, int col, short align,  
  176.             String val) {  
  177.         HSSFCell cell = row.createCell(col);  
  178.         cell.setCellType(HSSFCell.ENCODING_UTF_16);  
  179.         cell.setCellValue(new HSSFRichTextString(val));  
  180.         HSSFCellStyle cellstyle = wb.createCellStyle();  
  181.         cellstyle.setAlignment(align);  
  182.         cell.setCellStyle(cellstyle);  
  183.     }  
  184.   
  185.     /** 
  186.      * 创建合计行 
  187.      *  
  188.      * @param colSum 
  189.      *            需要合并到的列索引 
  190.      * @param cellValue 
  191.      */  
  192.     @SuppressWarnings("deprecation")  
  193.     public void createLastSumRow(int colSum, String[] cellValue) {  
  194.   
  195.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  196.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐  
  197.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐  
  198.         cellStyle.setWrapText(true);// 指定单元格自动换行  
  199.   
  200.         // 单元格字体  
  201.         HSSFFont font = wb.createFont();  
  202.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  203.         font.setFontName("宋体");  
  204.         font.setFontHeight((short250);  
  205.         cellStyle.setFont(font);  
  206.         // 获取工作表最后一行  
  207.         HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));  
  208.         HSSFCell sumCell = lastRow.createCell(0);  
  209.   
  210.         sumCell.setCellValue(new HSSFRichTextString("合计"));  
  211.         sumCell.setCellStyle(cellStyle);  
  212.         // 合并 最后一行的第零列-最后一行的第一列  
  213.         sheet.addMergedRegion(new Region(sheet.getLastRowNum(), (short0,  
  214.                 sheet.getLastRowNum(), (short) colSum));// 指定合并区域  
  215.   
  216.         for (int i = 2; i < (cellValue.length + 2); i++) {  
  217.             // 定义最后一行的第三列  
  218.             sumCell = lastRow.createCell(i);  
  219.             sumCell.setCellStyle(cellStyle);  
  220.             // 定义数组 从0开始。  
  221.             sumCell.setCellValue(new HSSFRichTextString(cellValue[i - 2]));  
  222.         }  
  223.     }  
  224.   
  225.     /** 
  226.      * 输入EXCEL文件 
  227.      *  
  228.      * @param fileName 
  229.      *            文件名 
  230.      */  
  231.     public void outputExcel(String fileName) {  
  232.         FileOutputStream fos = null;  
  233.         try {  
  234.             fos = new FileOutputStream(new File(fileName));  
  235.             wb.write(fos);  
  236.             fos.close();  
  237.         } catch (FileNotFoundException e) {  
  238.             e.printStackTrace();  
  239.         } catch (IOException e) {  
  240.             e.printStackTrace();  
  241.         }  
  242.     }  
  243.   
  244.     /** 
  245.      * @return the sheet 
  246.      */  
  247.     public HSSFSheet getSheet() {  
  248.         return sheet;  
  249.     }  
  250.   
  251.     /** 
  252.      * @param sheet 
  253.      *            the sheet to set 
  254.      */  
  255.     public void setSheet(HSSFSheet sheet) {  
  256.         this.sheet = sheet;  
  257.     }  
  258.   
  259.     /** 
  260.      * @return the wb 
  261.      */  
  262.     public HSSFWorkbook getWb() {  
  263.         return wb;  
  264.     }  
  265.   
  266.     /** 
  267.      * @param wb 
  268.      *            the wb to set 
  269.      */  
  270.     public void setWb(HSSFWorkbook wb) {  
  271.         this.wb = wb;  
  272.     }  
  273. }  


 

 

3.这里只使用了Servlet,可以根据需要来使用在不同的地方。

[java] view plaincopyprint?
  1. package com.jeelon.exportExcle;  
  2.   
  3. import java.io.BufferedOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStream;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  16. import org.apache.poi.hssf.usermodel.HSSFFont;  
  17. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  18. import org.apache.poi.hssf.usermodel.HSSFRow;  
  19. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  20. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  21.   
  22. @SuppressWarnings("serial")  
  23. public class OutputExcel extends HttpServlet {  
  24.   
  25.     protected void doGet(HttpServletRequest request,  
  26.             HttpServletResponse response) throws ServletException, IOException {  
  27.         this.doPost(request, response);  
  28.     }  
  29.   
  30.     protected void doPost(HttpServletRequest request,  
  31.             HttpServletResponse response) throws ServletException, IOException {  
  32.         System.out.println("helloworld");  
  33.         List<Student> list = new ArrayList<Student>();  
  34.   
  35.         Student student1 = new Student(1"Jeelon"21"贵阳市 ""15085943968",  
  36.                 '男');  
  37.         Student student2 = new Student(2"fengxu"21"贵阳市 ""15085943968",  
  38.                 '男');  
  39.         Student student3 = new Student(3"jerry"21"贵阳市 ""15085943968",  
  40.                 '男');  
  41.         Student student4 = new Student(4"merry"21"贵阳市 ""15085943968",  
  42.                 '男');  
  43.         Student student5 = new Student(5"lariiy"21"贵阳市 ""15085943968",  
  44.                 '男');  
  45.         Student student6 = new Student(6"monr"21"贵阳市 ""15085943968",  
  46.                 '男');  
  47.         Student student7 = new Student(7"join"21"贵阳市 ""15085943968",  
  48.                 '男');  
  49.         Student student8 = new Student(8"jay chou"21"贵阳市 ",  
  50.                 "15085943968"'男');  
  51.         Student student9 = new Student(9"laonb"21"贵阳市 ""15085943968",  
  52.                 '男');  
  53.         Student student0 = new Student(0"mudg"21"贵阳市 ""15085943968",  
  54.                 '男');  
  55.   
  56.         list.add(student1);  
  57.         list.add(student2);  
  58.         list.add(student3);  
  59.         list.add(student4);  
  60.         list.add(student5);  
  61.         list.add(student6);  
  62.         list.add(student7);  
  63.         list.add(student8);  
  64.         list.add(student9);  
  65.         list.add(student0);  
  66.   
  67.         String fileName = "导出Excel.xls";  
  68.         fileName = new String(fileName.getBytes("GBK"), "iso8859-1");  
  69.         response.reset();  
  70.         response.setHeader("Content-Disposition""attachment;filename="  
  71.                 + fileName);// 指定下载的文件名  
  72.         response.setContentType("application/vnd.ms-excel");  
  73.         response.setHeader("Pragma""no-cache");  
  74.         response.setHeader("Cache-Control""no-cache");  
  75.         response.setDateHeader("Expires"0);  
  76.         OutputStream output = response.getOutputStream();  
  77.         BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);  
  78.   
  79.         // 定义单元格报头  
  80.         String worksheetTitle = "Excel导出Student信息";  
  81.   
  82.         HSSFWorkbook wb = new HSSFWorkbook();  
  83.   
  84.         // 创建单元格样式  
  85.         HSSFCellStyle cellStyleTitle = wb.createCellStyle();  
  86.         // 指定单元格居中对齐  
  87.         cellStyleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  88.         // 指定单元格垂直居中对齐  
  89.         cellStyleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  90.         // 指定当单元格内容显示不下时自动换行  
  91.         cellStyleTitle.setWrapText(true);  
  92.         // ------------------------------------------------------------------  
  93.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  94.         // 指定单元格居中对齐  
  95.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  96.         // 指定单元格垂直居中对齐  
  97.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  98.         // 指定当单元格内容显示不下时自动换行  
  99.         cellStyle.setWrapText(true);  
  100.         // ------------------------------------------------------------------  
  101.         // 设置单元格字体  
  102.         HSSFFont font = wb.createFont();  
  103.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  104.         font.setFontName("宋体");  
  105.         font.setFontHeight((short200);  
  106.         cellStyleTitle.setFont(font);  
  107.   
  108.         // 工作表名  
  109.         String id = "id";  
  110.         String name = "name";  
  111.         String age = "age";  
  112.         String address = "address";  
  113.         String tel = "tel";  
  114.         String sex = "sex";  
  115.   
  116.         HSSFSheet sheet = wb.createSheet();  
  117.         ExportExcel exportExcel = new ExportExcel(wb, sheet);  
  118.         // 创建报表头部  
  119.         exportExcel.createNormalHead(worksheetTitle, 6);  
  120.         // 定义第一行  
  121.         HSSFRow row1 = sheet.createRow(1);  
  122.         HSSFCell cell1 = row1.createCell(0);  
  123.   
  124.         //第一行第一列  
  125.           
  126.         cell1.setCellStyle(cellStyleTitle);  
  127.         cell1.setCellValue(new HSSFRichTextString(id));  
  128.         //第一行第er列  
  129.         cell1 = row1.createCell(1);  
  130.         cell1.setCellStyle(cellStyleTitle);  
  131.         cell1.setCellValue(new HSSFRichTextString(name));  
  132.   
  133.         //第一行第san列  
  134.         cell1 = row1.createCell(2);  
  135.         cell1.setCellStyle(cellStyleTitle);  
  136.         cell1.setCellValue(new HSSFRichTextString(age));  
  137.   
  138.         //第一行第si列  
  139.         cell1 = row1.createCell(3);  
  140.         cell1.setCellStyle(cellStyleTitle);  
  141.         cell1.setCellValue(new HSSFRichTextString(address));  
  142.   
  143.         //第一行第wu列  
  144.         cell1 = row1.createCell(4);  
  145.         cell1.setCellStyle(cellStyleTitle);  
  146.         cell1.setCellValue(new HSSFRichTextString(tel));  
  147.   
  148.         //第一行第liu列  
  149.         cell1 = row1.createCell(5);  
  150.         cell1.setCellStyle(cellStyleTitle);  
  151.         cell1.setCellValue(new HSSFRichTextString(sex));  
  152.   
  153.         //第一行第qi列  
  154.         cell1 = row1.createCell(6);  
  155.         cell1.setCellStyle(cellStyleTitle);  
  156.         cell1.setCellValue(new HSSFRichTextString(sex));  
  157.   
  158.           
  159.         //定义第二行  
  160.         HSSFRow row = sheet.createRow(2);  
  161.         HSSFCell cell = row.createCell(1);  
  162.         Student student = new Student();  
  163.         for (int i = 0; i < list.size(); i++) {  
  164.             student = list.get(i);  
  165.             row = sheet.createRow(i + 2);  
  166.   
  167.             cell = row.createCell(0);  
  168.             cell.setCellStyle(cellStyle);  
  169.             cell.setCellValue(new HSSFRichTextString(student.getId() + ""));  
  170.               
  171.             cell = row.createCell(1);  
  172.             cell.setCellStyle(cellStyle);  
  173.             cell.setCellValue(new HSSFRichTextString(student.getName()));  
  174.               
  175.             cell = row.createCell(2);  
  176.             cell.setCellStyle(cellStyle);  
  177.             cell.setCellValue(new HSSFRichTextString(student.getAge() + ""));  
  178.               
  179.             cell = row.createCell(3);  
  180.             cell.setCellStyle(cellStyle);  
  181.             cell.setCellValue(new HSSFRichTextString(student.getAddress() + ""));  
  182.               
  183.             cell = row.createCell(4);  
  184.             cell.setCellStyle(cellStyle);  
  185.             cell.setCellValue(new HSSFRichTextString(student.getAddress()));  
  186.               
  187.             cell = row.createCell(5);  
  188.             cell.setCellStyle(cellStyle);  
  189.             cell.setCellValue(new HSSFRichTextString(student.getTel()));  
  190.               
  191.             cell = row.createCell(6);  
  192.             cell.setCellValue(new HSSFRichTextString(String.valueOf(student.getSex())));  
  193.             cell.setCellStyle(cellStyle);  
  194.               
  195.         }  
  196.         try {  
  197.             bufferedOutPut.flush();  
  198.             wb.write(bufferedOutPut);  
  199.             bufferedOutPut.close();  
  200.         } catch (IOException e) {  
  201.             e.printStackTrace();  
  202.             System.out.println("Output   is   closed ");  
  203.         } finally {  
  204.             list.clear();  
  205.         }  
  206.     }  
  207. }  


4.由于使用的是Servlet  ,当然还有配置Servlet哦  这里就不再说乐吧  相信他对于你是so easy!

 

5.前台jsp页面:

 

[html] view plaincopyprint?
  1. 导出数据到excel  
  2.         <form action="excel" method="post">  
  3.             <input type="submit" name="" value="导出">  
  4.         </form>  

0 0
原创粉丝点击