报表生成poi----java操作java对象生成execl表单

 1.Apache POI简介

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 POI 的功能。

2.POI结构

HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF - 提供读写Microsoft Word DOC格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读Microsoft Visio格式档案的功能。
HPBF - 提供读Microsoft Publisher格式档案的功能。
HSMF - 提供读Microsoft Outlook格式档案的功能。

3.生成execl的代码

  1 package com.bjsxt.sxf.test;
  2 
  3 
  4 import java.io.File;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.OutputStream;
  9 import java.util.Date;
 10 
 11 import org.apache.poi.hssf.usermodel.HSSFSheet;
 12 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 13 import org.apache.poi.hssf.util.CellRangeAddress;
 14 import org.apache.poi.hssf.util.HSSFColor;
 15 import org.apache.poi.ss.usermodel.Cell;
 16 import org.apache.poi.ss.usermodel.CellStyle;
 17 import org.apache.poi.ss.usermodel.CreationHelper;
 18 import org.apache.poi.ss.usermodel.Font;
 19 import org.apache.poi.ss.usermodel.IndexedColors;
 20 import org.apache.poi.ss.usermodel.Row;
 21 import org.apache.poi.ss.usermodel.Workbook;
 22 
 23 
 24 /**
 25  * 操作java代码生成execl表格
 26 * @ClassName: JavaToExcel 
 27 * @Description: TODO(这里用一句话描述这个类的作用) 
 28 * @author 尚晓飞
 29 * @date 2014-10-9 上午10:21:54 
 30 *
 31  */
 32 public class JavaToExcel {
 33     
 34     public static void main(String[] args) throws IOException {
 35         //创建Workbook对象(这一个对象代表着对应的一个Excel文件)  
 36         //HSSFWorkbook表示以xls为后缀名的文件  
 37         HSSFWorkbook wb=new HSSFWorkbook();
 38         //获得CreationHelper对象,这个应该是一个帮助类  
 39         CreationHelper helper = wb.getCreationHelper(); 
 40         //创建Sheet并给名字(表示Excel的一个Sheet)  
 41         HSSFSheet sheet1 = wb.createSheet("student01");        
 42         //Row表示一行Cell表示一列  
 43         Row row = null;  
 44         Cell cell = null;  
 45         for(int i=0;i<60;i++){  
 46             //获得这个sheet的第i行  (行是从0开始的,0是第一行)
 47             row = sheet1.createRow(i);  
 48             //设置行长度自动             
 49             //row.setHeight((short)500);  
 50             row.setHeightInPoints(20);  
 51             //row.setZeroHeight(true);  
 52             for(int j=0;j<25;j++){         
 53                 //设置每个sheet每一列的宽度,自动,根据内容的最大长度确定。  
 54                 sheet1.autoSizeColumn(j, true);  
 55                 //创建一个基本的样式  
 56                CellStyle cellStyle =  JavaToExcel.createStyleCell(wb);  
 57                 //获得这一行的每j列  
 58                 cell = row.createCell(j);  
 59                 if(j==0){  
 60                     //设置文字在单元格里面的位置  
 61                     cellStyle = JavaToExcel.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_BOTTOM);  
 62                     //先创建字体样式,并把这个样式加到单元格的字体里面  
 63                     cellStyle.setFont(createFonts(wb));  
 64                     //把这个样式加到单元格里面  
 65                     cell.setCellStyle(cellStyle);                     
 66                     //给单元格设值  
 67                    if(i%2==0){
 68                        cell.setCellValue("尚晓飞是个大坏蛋dsafdsagfdsgserthgfdhytjfdsadfdsagrea"); 
 69                    }else{
 70                        cell.setCellValue("尚晓飞是个大坏蛋"); 
 71                    }
 72                     
 73                 }else if(j==1){  
 74                     //设置文字在单元格里面的位置  
 75                     cellStyle = JavaToExcel.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);  
 76                     //设置这个样式的格式(Format)  
 77                     cellStyle = JavaToExcel.setCellFormat(helper,cellStyle, "#,##0.0000");                    
 78                     //先创建字体样式,并把这个样式加到单元格的字体里面  
 79                     cellStyle.setFont(createFonts(wb));  
 80                     //把这个样式加到单元格里面  
 81                     cell.setCellStyle(cellStyle);  
 82                     //给单元格设值  
 83                     cell.setCellValue(new Date());  
 84                 }else if(j==2){  
 85                     cellStyle = JavaToExcel.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);                      
 86                     cellStyle.setFont(createFonts(wb));  
 87                     cell.setCellStyle(cellStyle);  
 88                     cell.setCellValue(helper.createRichTextString("RichString"+i+j));                     
 89                 }else if(j==3){  
 90                     cellStyle = JavaToExcel.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);  
 91                     cellStyle = JavaToExcel.setCellFormat(helper,cellStyle, "MM-yyyy-dd");  
 92                     cell.setCellStyle(cellStyle);  
 93                     cell.setCellValue(new Date());  
 94                 }else if(j==24){  
 95                     cellStyle = JavaToExcel.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);  
 96                     cellStyle.setFont(createFonts(wb));  
 97                     //设置公式  
 98                     cell.setCellFormula("SUM(E"+(i+1)+":X"+(i+1)+")");                    
 99                 }else{                    
100                     cellStyle = JavaToExcel.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);  
101                     cellStyle = JavaToExcel.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),CellStyle.SOLID_FOREGROUND);  
102                     cell.setCellStyle(cellStyle);  
103                     cell.setCellValue("");  
104                 }  
105             } 
106             
107             
108             
109         }  
110         
111       //合并单元格
112         //参数含义:new CellRangeAddress(a, b, c,d)
113         //a和c:第几行  b和d是第几列   行和列的下标从0开始   0表示第一行或第一列
114         /**
115          * 重点注意事项:
116           1.单元格CELL和ROW对象下标都是从0开始的。
117           2.单元格合并时new CellRangeAddress(a, b, c,d)a的值的行号必须要比c的行号小,如果大于c就不能正常合并单元格
118           3.合并单元格的时候要合并的单单元格必须先创建,这样方便后面再次获取这个单元格来填充数据,主要就是因为合并时不能由后向前进行合并引起的。 
119          */
120         sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0,24));
121         Cell cell2=sheet1.getRow(0).getCell(0);
122         cell2.setCellValue("将java中的对象转换成execl表格并保存的表内容");
123       
124         
125         //输出  
126         OutputStream os;
127         try {
128             os = new FileOutputStream(new File("c://JavaToExcel.xls"));
129               wb.write(os);  
130               os.close();     
131         } catch (FileNotFoundException e) {
132             // TODO Auto-generated catch block
133             e.printStackTrace();
134         }  
135          
136         
137     }
138     
139     
140     /** 
141      * 边框 
142      * @param wb 
143      * @return 
144      */  
145     public static CellStyle createStyleCell(Workbook wb){  
146         CellStyle cellStyle = wb.createCellStyle();  
147         //设置一个单元格边框样式  
148         cellStyle.setBorderBottom(CellStyle.BORDER_THIN);  
149         cellStyle.setBorderTop(CellStyle.BORDER_THIN);  
150         cellStyle.setBorderLeft(CellStyle.BORDER_THIN);  
151         cellStyle.setBorderRight(CellStyle.BORDER_THIN);  
152         /**
153          * 
154              CellStyle.BORDER_DOUBLE      双边线   
155              CellStyle.BORDER_THIN        细边线   
156              CellStyle.BORDER_MEDIUM      中等边线   
157              CellStyle.BORDER_DASHED      虚线边线   
158              CellStyle.BORDER_HAIR        小圆点虚线边线   
159              CellStyle.BORDER_THICK       粗边线  
160          */
161         //设置一个单元格边框颜色  
162         cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());  
163         cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());  
164         cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
165         cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());          
166         return cellStyle;  
167     }  
168     /** 
169      * 设置文字在单元格里面的位置 
170      * CellStyle.ALIGN_CENTER 
171      * CellStyle.VERTICAL_CENTER 
172      * @param cellStyle 
173      * @param halign 
174      * @param valign 
175      * @return 
176      */  
177     public static CellStyle setCellStyleAlignment(CellStyle cellStyle,short halign,short valign){  
178         //设置上下  
179         cellStyle.setAlignment(CellStyle.ALIGN_LEFT);  
180         //设置左右  
181         cellStyle.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);  
182         return cellStyle;  
183     }  
184     /** 
185      * 格式化单元格 
186      * 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找 
187      * @param cellStyle 
188      * @param fmt 
189      * @return 
190      */  
191     public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){  
192         //还可以用其它方法创建format  
193         cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));  
194         return cellStyle;  
195     }  
196     /** 
197      * 前景和背景填充的着色 
198      * @param cellStyle 
199      * @param bg IndexedColors.ORANGE.getIndex(); 
200      * @param fg IndexedColors.ORANGE.getIndex(); 
201      * @param fp CellStyle.SOLID_FOREGROUND 
202      * @return 
203      */  
204     public static CellStyle setFillBackgroundColors(CellStyle cellStyle,short bg,short fg,short fp){  
205         //cellStyle.setFillBackgroundColor(bg);  
206         cellStyle.setFillForegroundColor(fg);  
207         cellStyle.setFillPattern(fp);  
208         return cellStyle;  
209     }  
210     /** 
211      * 设置字体 
212      * @param wb 
213      * @return 
214      */  
215     public static Font createFonts(Workbook wb){  
216         //创建Font对象  
217         Font font = wb.createFont();  
218         //设置字体  
219         font.setFontName("黑体");  
220         //着色  
221         font.setColor(HSSFColor.BLUE.index);  
222         //斜体  
223         font.setItalic(true);  
224         //字体大小  
225         font.setFontHeight((short)300);  
226         return font;  
227     }  
228 }
View Code

 

示例:生成报表【此示例生成学生信息表(应用到阿帕奇的poi和struts2下载)】

一:struts.xml关于生成报表的下载配置

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7     <!-- 如果请求地址=actionName!methodName ,则该配置需要进行设置,否则访问地址错误-->
 8     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
 9     
10     <!-- 开发模式 -->
11     <constant name="struts.devMode" value="true" />
12     
13     <!-- 编码格式过滤 -->
14     <constant name="struts.i18n.encoding" value="utf-8"></constant>
15     
16    <!-- 告诉struts.xml不要自己通过反射new,对象,去spring的ioc容器中找
17             action中的class='spring中Ioc容器中对象的id'
18             annotation注解生成对象默认情况下id值为是:类名首字符小写
19             需要加jar包struts-spring-plugin..jar
20          -->
21     <constant name="struts.objectFactory" value="spring"></constant>
22     
23     
24     <package name="default" namespace="/" extends="struts-default">
25         <!-- actionName!methodName请求方式的配置 -->
26         <action name="StudentAction" class="StudentAction">
27             <result name="success">/page/success.jsp</result>
28             <!-- 生成报表的下载返回 -->
29             <result name="inputStu" type="stream">
30                     <param name="contentType">application/vnd.ms-excel;charset=UTF-8</param>
31                     <!-- 下载页文件名的显示,action中的属性 -->
32                     <param name="contentDisposition">attachment;fileName="${fileName}"</param>
33                     <!-- action中输入流属性的名字 -->
34                     <param name="inputName">stuReport</param>
35                     <!-- 读取字节数的大小1kb -->
36                     <param name="bufferSize">1024</param>
37             </result>
38         </action>
39         <action name="PowerAction" class="PowerAction">
40             <result name="success">/page/success.jsp</result>
41         </action>
42     </package>
43 </struts>
View Code

二:生成报表的action类,以及方法和下载时应该设置的属性。与struts.xml配置相对应

  1 package com.bjsxt.sxf.action;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.InputStream;
  7 import java.io.UnsupportedEncodingException;
  8 
  9 import org.apache.struts2.ServletActionContext;
 10 
 11 import com.bjsxt.sxf.po.Student;
 12 import com.bjsxt.sxf.service.ClassRoomService;
 13 import com.bjsxt.sxf.service.StudentService;
 14 
 15 
 16 
 17 
 18 public class StudentAction {
 19     private StudentService studentService;
 20     private ClassRoomService classRoomService;
 21     
 22     //struts2下载两个属性
 23     private String fileName; //生成的execl的文件名
 24     private InputStream stuReport;//将项目根目录下生成的execl文件读入的客户端内存中的输入流
 25     
 26     
 27     
 28     //此get方法是为了
 29     /**
 30      *     ISO8859-1是页面上数据传输的格式,
 31         new String(fileName.getBytes("utf-8"),"iso8859-1");
 32         utf-8是你java项目格式(根据实际项目变更),目的是为了将中文文件名正确显示在页面上
 33      */
 34     
 35     public String getFileName() {
 36         try {
 37             fileName=new String(this.fileName.getBytes("utf-8"),"ISO8859-1");
 38         } catch (UnsupportedEncodingException e) {
 39             // TODO Auto-generated catch block
 40             e.printStackTrace();
 41         }
 42         return fileName;
 43     }
 44 
 45     public void setFileName(String fileName) {
 46         this.fileName = fileName;
 47     }
 48 
 49     public InputStream getStuReport() {
 50         return stuReport;
 51     }
 52 
 53     public void setStuReport(InputStream stuReport) {
 54         this.stuReport = stuReport;
 55     }
 56     
 57     
 58     
 59     /**当前台请求触发该方法,则先生成execl表格,存放在项目根目录指定的文件下。然后利用struts2的下载将该execl下载到请求客户端的电脑上
 60      * 生成学生信息execl表格,并下载
 61     * @Title: reportStudent 
 62     * @Description: TODO(这里用一句话描述这个方法的作用) 
 63     * @return
 64     * @return String    返回类型 
 65     * @author 尚晓飞
 66     * @date 2014-10-9 上午11:07:08
 67      */
 68     public String reportStudent(){
 69         try {
 70             fileName=studentService.stuList2Excel();
 71             String path=ServletActionContext.getServletContext().getRealPath("master")+File.separator+"report"+File.separator+fileName;
 72             stuReport=new FileInputStream(path);
 73         } catch (FileNotFoundException e) {
 74             // TODO Auto-generated catch block
 75             e.printStackTrace();
 76         }
 77         return "inputStu";
 78     }
 79     
 80     public String findById(){
 81         studentService.findById(1);
 82         return null;
 83     }
 84     
 85     public String findByIdClassRoom(){
 86         classRoomService.findById(1);
 87         return null;
 88     }
 89     
 90     
 91     
 92     
 93 
 94     public ClassRoomService getClassRoomService() {
 95         return classRoomService;
 96     }
 97 
 98     public void setClassRoomService(ClassRoomService classRoomService) {
 99         this.classRoomService = classRoomService;
100     }
101 
102     public StudentService getStudentService() {
103         return studentService;
104     }
105 
106     public void setStudentService(StudentService studentService) {
107         this.studentService = studentService;
108     }
109 
110     
111 
112     
113     
114     
115     
116 
117 }
View Code

三:生成execl表格的业务类,并将execl存入项目根目录指定文件下(省去dao层与数据库交互的方法)

  1 package com.bjsxt.sxf.service.impl;
  2 
  3 import java.io.File;
  4 import java.io.FileNotFoundException;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.OutputStream;
  8 import java.text.DateFormat;
  9 import java.text.SimpleDateFormat;
 10 import java.util.Date;
 11 import java.util.List;
 12 
 13 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 14 import org.apache.poi.hssf.usermodel.HSSFSheet;
 15 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 16 import org.apache.poi.hssf.util.CellRangeAddress;
 17 import org.apache.poi.hssf.util.HSSFColor;
 18 import org.apache.poi.ss.usermodel.Cell;
 19 import org.apache.poi.ss.usermodel.CellStyle;
 20 import org.apache.poi.ss.usermodel.CreationHelper;
 21 import org.apache.poi.ss.usermodel.Font;
 22 import org.apache.poi.ss.usermodel.IndexedColors;
 23 import org.apache.poi.ss.usermodel.Row;
 24 import org.apache.struts2.ServletActionContext;
 25 import org.hibernate.dialect.IngresDialect;
 26 
 27 import com.bjsxt.sxf.dao.StudentDao;
 28 import com.bjsxt.sxf.po.ClassRoom;
 29 import com.bjsxt.sxf.po.Student;
 30 import com.bjsxt.sxf.service.StudentService;
 31 /**
 32  * 学生的业务类
 33 * @ClassName: StudentServiceImpl 
 34 * @Description: TODO(这里用一句话描述这个类的作用) 
 35 * @author 尚晓飞
 36 * @date 2014-10-9 下午5:24:04 
 37 *
 38  */
 39 public class StudentServiceImpl implements StudentService{
 40     private StudentDao studentDao;
 41     
 42     /**
 43      * 添加一个学生
 44     * @Title: addStudent 
 45     * @Description: TODO(这里用一句话描述这个方法的作用)
 46     * @author 尚晓飞
 47     * @date 2014-10-9 下午5:24:29
 48     * @param student 
 49     * @see com.bjsxt.sxf.service.StudentService#addStudent(com.bjsxt.sxf.po.Student)
 50      */
 51     @Override
 52     public void addStudent(Student student) {
 53         // TODO Auto-generated method stub
 54         studentDao.add(student);
 55         
 56     }
 57     
 58     
 59     /**
 60      * 查询出指定id的学生
 61     * @Title: findById 
 62     * @Description: TODO(这里用一句话描述这个方法的作用)
 63     * @author 尚晓飞
 64     * @date 2014-10-9 下午5:24:42
 65     * @param id
 66     * @return 
 67     * @see com.bjsxt.sxf.service.StudentService#findById(java.lang.Integer)
 68      */
 69     @Override
 70     public Student findById(Integer id) {
 71         Student student=studentDao.find(id);
 72         ClassRoom cls=student.getClassRoom();
 73         System.out.println("StudentServiceImpl.findById()"+cls.getName());
 74         return student;
 75     }
 76 
 77     
 78     /**
 79      * 将学生信息生成excel表格,并写入项目根目录下
 80     * @Title: stuList2Excel 
 81     * @Description: TODO(这里用一句话描述这个方法的作用)
 82     * @author 尚晓飞
 83     * @date 2014-10-9 上午11:28:57
 84     * @return 
 85     * @see com.bjsxt.sxf.service.StudentService#stuList2Excel()
 86      */
 87     @Override
 88     public String stuList2Excel() {
 89         // TODO Auto-generated method stub
 90         //查询出所有学生的信息【要生成execl的java对象】
 91         List<Student> students=studentDao.queryAll();
 92         //标题行
 93         Date date=new Date();
 94         DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
 95         String tilte=format.format(date)+"学生信息表";
 96         
 97         //列名行
 98         String[] valueT={"学生id","学生姓名","学生性别","所在班级名称"};
 99         
100         //第一步:创建excel文件
101         //HSSFWorkbook表示以xls为后缀名的文件  
102         HSSFWorkbook wb=new HSSFWorkbook();
103         //获得CreationHelper对象,这个应该是一个帮助类  
104         CreationHelper helper = wb.getCreationHelper(); 
105         //创建Sheet并给名字(表示Excel的一个Sheet)  
106         HSSFSheet sheet1 = wb.createSheet("学生信息表");
107         HSSFCellStyle cellStyle = wb.createCellStyle();
108         
109         //设置单元格边框
110         //设置一个单元格边框样式  
111         cellStyle.setBorderBottom(CellStyle.BORDER_THICK);  
112         cellStyle.setBorderTop(CellStyle.BORDER_THICK);  
113         cellStyle.setBorderLeft(CellStyle.BORDER_THICK);  
114         cellStyle.setBorderRight(CellStyle.BORDER_THICK); 
115         
116         //设置一个单元格边框的颜色
117         cellStyle.setRightBorderColor(IndexedColors.GREEN.getIndex());  
118         cellStyle.setLeftBorderColor(IndexedColors.GREEN.getIndex());  
119         cellStyle.setBottomBorderColor(IndexedColors.GREEN.getIndex());  
120         cellStyle.setTopBorderColor(IndexedColors.GREEN.getIndex()); 
121         
122         //设置单元格内容显示的位置
123         //上下
124         cellStyle.setAlignment(CellStyle.ALIGN_CENTER);  
125         //设置左右  
126         cellStyle.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);  
127         
128         //设置字体
129         Font font=wb.createFont();
130         font.setFontName("黑体");
131         font.setColor(HSSFColor.RED.index);
132         font.setFontHeight((short)500);
133         cellStyle.setFont(font);
134         
135         //第二步:创建标题行(先创建单元格,再合并单元格)
136         Row titleRow=sheet1.createRow(0);
137         for(int i=0;i<valueT.length;i++){
138             Cell cell=titleRow.createCell(i);
139             cell.setCellStyle(cellStyle);
140             
141         }
142         //合并单元格
143         sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0,valueT.length-1));
144         Cell cellTitle=titleRow.getCell(0);
145         //标题行完成
146         cellTitle.setCellValue(tilte);
147         cellTitle.setCellStyle(cellStyle);
148         //设置列的宽度为内容的最大长度【设置列的显示宽度,防止不遮盖内容】
149         sheet1.autoSizeColumn(0, true);
150         
151         
152         
153         //第三步:创建列名行
154         Row rowT=sheet1.createRow(1);
155         for(int i=0;i<valueT.length;i++){
156             sheet1.autoSizeColumn(i, true);
157             Cell cellT=rowT.createCell(i);
158             cellT.setCellValue(valueT[i]);
159             cellT.setCellStyle(cellStyle);
160         }
161         
162         //第四步创建内容行
163         for(int a=0;a<students.size();a++){
164             Row row=sheet1.createRow(a+2);
165             Student student=students.get(a);
166             
167             //id
168             sheet1.autoSizeColumn(0, true);
169             Cell cellId=row.createCell(0);
170             cellId.setCellValue(student.getId());
171             cellId.setCellStyle(cellStyle);
172             
173             //姓名
174             sheet1.autoSizeColumn(1, true);
175             Cell cellName=row.createCell(1);
176             cellName.setCellValue(student.getName());
177             cellName.setCellStyle(cellStyle);
178             
179             //性别
180             sheet1.autoSizeColumn(2, true);
181             Cell cellSex=row.createCell(2);
182             cellSex.setCellValue(student.getSex());
183             cellSex.setCellStyle(cellStyle);
184             
185             //班级名称
186             sheet1.autoSizeColumn(3, true);
187             Cell cellClassName=row.createCell(3);
188             cellClassName.setCellValue(student.getClassRoom().getName());
189             cellClassName.setCellStyle(cellStyle);
190             
191             
192         }
193         
194         //输出保存的文件名
195         DateFormat format2=new SimpleDateFormat("yyyyMMddHHmmss");
196         String fileName=format2.format(date)+"学生信息表.xls";
197         
198         //创建一个存放学生信息表的文件在项目根目录下
199         File file=new File(ServletActionContext.getServletContext().getRealPath("master")+File.separator+"report");
200         if(!file.exists()){
201             file.mkdir();
202         }
203         //输出  
204         OutputStream os;
205         try {
206                //输出到项目根目录下
207                os = new FileOutputStream(file+File.separator+fileName);
208                wb.write(os);  
209                os.close();     
210         } catch (IOException e) {
211                      // TODO Auto-generated catch block
212                      e.printStackTrace();
213         } 
214                 
215         
216         
217         return fileName;
218     }
219 
220 
221 
222     public StudentDao getStudentDao() {
223         return studentDao;
224     }
225 
226     public void setStudentDao(StudentDao studentDao) {
227         this.studentDao = studentDao;
228     }
229     
230     
231 }
View Code

四:效果图

 

原文地址:https://www.cnblogs.com/shangxiaofei/p/4012737.html