下载 jxl.jar的地址
http://www.andykhan.com/jexcelapi/index.html
下载最新版的jexcelap,如jexcelapi_2_6.tar.gz
解压缩,将其中的jxl.jar导入工程
解决中文问题
写一个javaBean,利用JExcelApi来动态生成excel文档,我这里写一个最简单的,示意性的。复杂的你可能还要查询数据库什么的。
写一个jsp,来利用Test这个javabean输出excel文档。
这样就大功告成了,你用ie访问test_excel.jsp就能在ie里面打开动态生成的excel文档了。一点乱码也没有。
也许有人会问:response.reset();可不可以不要这一句,我的建议是一定要写,除非你能保证response的buffer里面没有别的东西。
还有人也许会问:我在jsp开头加上<%@page contentType="application/vnd.ms-excel;charset=GBK" %>这一句,去掉response.setContentType("application/vnd.ms-excel");行不行?回答这个问题很简 单,就是查看jsp服务器编译jsp后生成的java代码,如果改成这样,我的welogic7编译test_excel.jsp后生成的java文件的 示意性代码是这样的:
很明显,屏蔽response.setContentType("application/vnd.ms-excel");后,在 Test.writeExcel(response.getOutputStream());之前,response.reset(); 之后没有设置response contenttype的正确类型,当然输出为乱码了。而正确输出excel的jsp的编译后源码是这样的:
大家可以看到在response.reset();之后,Test.writeExcel(response.getOutputStream());之前正确的设置了response的输出内容。所以输出就正常了。
ok,这样你就可以写一个类来处理这个文件了,我们在struts里通常用action 类来做这个工作
http://www.andykhan.com/jexcelapi/index.html
下载最新版的jexcelap,如jexcelapi_2_6.tar.gz
解压缩,将其中的jxl.jar导入工程
解决中文问题
写一个javaBean,利用JExcelApi来动态生成excel文档,我这里写一个最简单的,示意性的。复杂的你可能还要查询数据库什么的。
- ///Test.java///
- package com.jagie.test;
- import java.io.*;
- import jxl.*;
- import jxl.write.*;
- import jxl.format.*;
- import java.util.*;
- import java.awt.Color;
- public class Test{
- public static void writeExcel(OutputStream os) throws Exception {
- jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);
- jxl.write.WritableSheet ws = wwb.createSheet("TestSheet1", 0);
- jxl.write.Label labelC = new jxl.write.Label(0, 0, "我爱中国");
- ws.addCell(labelC);
- jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,20, WritableFont.BOLD, false,
- UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.GREEN);
- jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
- wcfFC.setBackground(jxl.format.Colour.RED);
- labelC = new jxl.write.Label(6, 0, "中国爱我",wcfFC);
- ws.addCell(labelC);
- //写入Exel工作表
- wwb.write();
- //关闭Excel工作薄对象
- wwb.close();
- }
- //最好写一个这样的main方法来测试一下你的这个class是否写好了。
- public static void main(String[] args)throws Exception{
- File f=new File("kk.xls");
- f.createNewFile();
- writeExcel(new FileOutputStream(f));
- }
- }
- ///test_excel.jsp//
- <%@page import="com.jagie.test.Test" %>
- <%
- response.reset();
- response.setContentType("application/vnd.ms-excel");
- Test.writeExcel(response.getOutputStream());
- %>
也许有人会问:response.reset();可不可以不要这一句,我的建议是一定要写,除非你能保证response的buffer里面没有别的东西。
还有人也许会问:我在jsp开头加上<%@page contentType="application/vnd.ms-excel;charset=GBK" %>这一句,去掉response.setContentType("application/vnd.ms-excel");行不行?回答这个问题很简 单,就是查看jsp服务器编译jsp后生成的java代码,如果改成这样,我的welogic7编译test_excel.jsp后生成的java文件的 示意性代码是这样的:
- public void _jspService(javax.servlet.http.HttpServletRequest request,
- javax.servlet.http.HttpServletResponse response) throws java.io.IOException,
- javax.servlet.ServletException {
- // declare and set well-known variables:
- javax.servlet.ServletConfig config = getServletConfig();
- javax.servlet.ServletContext application = config.getServletContext();
- javax.servlet.jsp.tagext.Tag _activeTag = null;
- // variables for Tag extension protocol
- Object page = this;
- javax.servlet.jsp.JspWriter out;
- javax.servlet.jsp.PageContext pageContext =
- javax.servlet.jsp.JspFactory.getDefaultFactory().getPageContext(this,
- request, response, null, true, 8192, true);
- response.setHeader("Content-Type", "application/vnd.ms-excel; charset=GBK");
- out = pageContext.getOut();
- JspWriter _originalOut = out;
- javax.servlet.http.HttpSession session = request.getSession(true);
- try { // error page try block
- response.setContentType("application/vnd.ms-excel;charset=GBK");
- out.print("/r/n/r/n/r/n/r/n");
- out.print("/r/n");
- //[ /test_excel.jsp; Line: 6]
- response.reset(); //[ /test_excel.jsp; Line: 7]
- //response.setContentType("application/vnd.ms-excel");
- //[ /test_excel.jsp; Line: 8]
- Test.writeExcel(response.getOutputStream()); //[ /test_excel.jsp; Line: 9]
- } catch (Throwable __ee) {
- while (out != null && out != _originalOut) out = pageContext.popBody();
- ((weblogic.servlet.jsp.PageContextImpl)pageContext).handlePageException((Throwable)__ee);
- }
- //before final close brace...
- }
- public void _jspService(javax.servlet.http.HttpServletRequest request,
- javax.servlet.http.HttpServletResponse response) throws java.io.IOException,
- javax.servlet.ServletException
- {
- // declare and set well-known variables:
- javax.servlet.ServletConfig config = getServletConfig();
- javax.servlet.ServletContext application = config.getServletContext();
- javax.servlet.jsp.tagext.Tag _activeTag = null;
- // variables for Tag extension protocol
- Object page = this;
- javax.servlet.jsp.JspWriter out;
- javax.servlet.jsp.PageContext pageContext =
- javax.servlet.jsp.JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
- out = pageContext.getOut();
- JspWriter _originalOut = out;
- javax.servlet.http.HttpSession session = request.getSession(true);
- try { // error page try block
- out.print("/r/n");
- //[ /test_excel.jsp; Line: 2]
- response.reset(); //[ /test_excel.jsp; Line: 3]
- response.setContentType("application/vnd.ms-excel"); //[ /test_excel.jsp; Line: 4]
- Test.writeExcel(response.getOutputStream()); //[ /test_excel.jsp; Line: 5]
- } catch (Throwable __ee) {
- while (out != null && out != _originalOut) out = pageContext.popBody();
- ((weblogic.servlet.jsp.PageContextImpl)pageContext).handlePageException((Throwable)__ee);
- }
- //before final close brace...
- }
最后,我来写写从jsp页面传入一个excel然后读取数据的过程吧
Struts 有个标签专门用来上传文件的
<td > <html:file property="file" id="file"/> </td>
你点了“浏览”按钮,文件传到那里去了呢?嗯,你要在form bean里面接收它,就是在你的xxxForm.java 里加上这样的代码
- private FormFile file;
- public FormFile getFile(){
- return this.file;
- }
- public void setFile(FormFile file){
- this.file=file;
- }
- private String fname;
- public String getFname(){
- return this.fname;
- }
- public void setFname(String fname){
- this.fname=fname;
- }
- private String size;
- public String getSize(){
- return this.size;
- }
- public void setSize(String size){
- this.size=size;
- }
- xxxAction.java
- public ActionForward save(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- String dir=servlet.getServletContext().getRealPath("/upload");//获取存放文件的文件夹的路径
- FormFile file = xxForm.getFile();//获取传上来的文件
- String fileName=null;
- String fname=file.getFileName();
- String size=Integer.toString(file.getFileSize())+"bytes";
- if(fname==null || fname.equals("")) ;
- else
- try{
- InputStream streamIn=file.getInputStream();
- OutputStream streamOut=new FileOutputStream(dir+"/"+fname);
- int bytesRead=0;
- byte[] buffer=new byte[8192];
- while((bytesRead=streamIn.read(buffer,0,8192))!=-1){
- streamOut.write(buffer,0,bytesRead);
- }
- streamOut.close();
- streamIn.close();
- xxForm.setFname(fname);
- xxForm.setSize(size);
- file.destroy();
- }
- catch(Exception e) {
- return mapping.findForward("error");
- }
- if (fname != null) {
- List excellist = getDataFromExcel(dir+"/"+fname); //要对excel文件进行处理啦
- File uploadFile = new File(dir+"/"+fname);
- uploadFile.delete();
- }
- }
- private List getDataFromExcel(String dir){
- Workbook workbook; //工作簿
- workbook = Workbook.getWorkbook(new File(dir));
- Sheet sheet = workbook.getSheet(0); // '0' 表示获取你的第一个sheet
- for(int column=0;column<sheet.getColumns();column++){
- for(int row=0;row<sheet.getRows();();row++){
- Cell cell=sheet.getCell(column ,row); //读出每一个单元格里面的内容
- System.out.println(cell);
- }
- }