论坛首页 Java企业应用论坛

java操作Excel、PDF文件

浏览 84108 次
该帖已经被评为精华帖
作者 正文
   发表时间:2006-10-09  
下面这些是在开发中用到的一些东西,有的代码贴的不是完整的,只是贴出了关于操作EXCEL的代码:


jxl是一个*国人写的java操作excel的工具, 在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI。其中功能相对POI比较弱一点。但jExcelAPI对中文支持非常好,API是纯Java的, 并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。 另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。

使用如下:

搭建环境

将下载后的文件解包,得到jxl.jar,放入classpath,安装就完成了。

基本操作

一、创建文件

拟生成一个名为“test.xls”的Excel文件,其中第一个工作表被命名为
“第一页”,大致效果如下:
 package  test;

 // 生成Excel的类 
 import  java.io.File;

 import  jxl.Workbook;
 import  jxl.write.Label;
 import  jxl.write.WritableSheet;
 import  jxl.write.WritableWorkbook;

 public   class  CreateExcel   {
     public   static   void  main(String args[])   {
         try    {
             //  打开文件 
             WritableWorkbook book  =  Workbook.createWorkbook( new  File( " test.xls " ));
             //  生成名为“第一页”的工作表,参数0表示这是第一页 
             WritableSheet sheet  =  book.createSheet( " 第一页 " ,  0 );
             //  在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
             //  以及单元格内容为test 
             Label label  =   new  Label( 0 ,  0 ,  " test " );

             //  将定义好的单元格添加到工作表中 
             sheet.addCell(label);

             /**/ /* 
             * 生成一个保存数字的单元格 必须使用Number的完整包路径,否则有语法歧义 单元格位置是第二列,第一行,值为789.123
              */ 
            jxl.write.Number number  =   new  jxl.write.Number( 1 ,  0 ,  555.12541 );
            sheet.addCell(number);

             //  写入数据并关闭文件 
             book.write();
            book.close();

        }   catch  (Exception e)   {
            System.out.println(e);
        } 
    } 
} 
 


   编译执行后,会产生一个Excel文件。

三、读取文件

以刚才我们创建的Excel文件为例,做一个简单的读取操作,程序代码如下:
 package  test;

 // 读取Excel的类 
 import  java.io.File;

 import  jxl.Cell;
 import  jxl.Sheet;
 import  jxl.Workbook;

 public   class  ReadExcel   {
     public   static   void  main(String args[])   {
         try    {
            Workbook book  =  Workbook.getWorkbook( new  File( " test.xls " ));
             //  获得第一个工作表对象 
             Sheet sheet  =  book.getSheet( 0 );
             //  得到第一列第一行的单元格 
             Cell cell1  =  sheet.getCell( 0 ,  0 );
            String result  =  cell1.getContents();
            System.out.println(result);
            book.close();
        }   catch  (Exception e)   {
            System.out.println(e);
        } 
    } 
} 
 


  程序执行结果:test

四、修改文件
利用jExcelAPI可以修改已有的Excel文件,修改Excel文件的时候,除了打开文件的方式不同之外,
其他操作和创建Excel是一样的。下面的例子是在我们已经生成的Excel文件中添加一个工作表:
 package  test;

 import  java.io.File;

 import  jxl.Workbook;
 import  jxl.write.Label;
 import  jxl.write.WritableSheet;
 import  jxl.write.WritableWorkbook;

 public   class  UpdateExcel   {
     public   static   void  main(String args[])   {
         try    {
             //  Excel获得文件 
             Workbook wb  =  Workbook.getWorkbook( new  File( " test.xls " ));
             //  打开一个文件的副本,并且指定数据写回到原文件 
             WritableWorkbook book  =  Workbook.createWorkbook( new  File( " test.xls " ),
                    wb);
             //  添加一个工作表 
             WritableSheet sheet  =  book.createSheet( " 第二页 " ,  1 );
            sheet.addCell( new  Label( 0 ,  0 ,  " 第二页的测试数据 " ));
            book.write();
            book.close();
        }   catch  (Exception e)   {
            System.out.println(e);
        } 
    } 
} 
 


其他操作

一、 数据格式化

在Excel中不涉及复杂的数据类型,能够比较好的处理字串、数字和日期已经能够满足一般的应用。

1、 字串格式化

字符串的格式化涉及到的是字体、粗细、字号等元素,这些功能主要由WritableFont和
WritableCellFormat类来负责。假设我们在生成一个含有字串的单元格时,使用如下语句,
为方便叙述,我们为每一行命令加了编号:
 WritableFont font1 = 
  new  WritableFont(WritableFont.TIMES, 16 ,WritableFont.BOLD); ①

 WritableCellFormat format1 = new  WritableCellFormat(font1); ②

 Label label = new  Label( 0 , 0 ,”data  4  test”,format1) ③

 
  其中①指定了字串格式:字体为TIMES,字号16,加粗显示。WritableFont有非常丰富的
 构造子,供不同情况下使用,jExcelAPI的java-doc中有详细列表,这里不再列出。

 ②处代码使用了WritableCellFormat类,这个类非常重要,通过它可以指定单元格的各种
 属性,后面的单元格格式化中会有更多描述。

 ③处使用了Label类的构造子,指定了字串被赋予那种格式。

 在WritableCellFormat类中,还有一个很重要的方法是指定数据的对齐方式,比如针对我们
 上面的实例,可以指定:

   // 把水平对齐方式指定为居中 
  format1.setAlignment(jxl.format.Alignment.CENTRE);

  // 把垂直对齐方式指定为居中 
  format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
 

二、单元格操作

Excel中很重要的一部分是对单元格的操作,比如行高、列宽、单元格合并等,所幸jExcelAPI
提供了这些支持。这些操作相对比较简单,下面只介绍一下相关的API。

1、 合并单元格
  WritableSheet.mergeCells( int  m, int  n, int  p, int  q); 

  // 作用是从(m,n)到(p,q)的单元格全部合并,比如: 
  WritableSheet sheet = book.createSheet(“第一页”, 0 );

  // 合并第一列第一行到第六列第一行的所有单元格 
  sheet.mergeCells( 0 , 0 , 5 , 0 );
 

合并既可以是横向的,也可以是纵向的。合并后的单元格不能再次进行合并,否则会触发异常。

2、 行高和列宽
  WritableSheet.setRowView( int  i, int  height);

  // 作用是指定第i+1行的高度,比如:

  // 将第一行的高度设为200 
  sheet.setRowView( 0 , 200 );

 WritableSheet.setColumnView( int  i, int  width);

  // 作用是指定第i+1列的宽度,比如:

  // 将第一列的宽度设为30 
  sheet.setColumnView( 0 , 30 );
  
  


jExcelAPI还有其他的一些功能,比如插入图片等,这里就不再一一介绍,读者可以自己探索。

其中:如果读一个excel,需要知道它有多少行和多少列,如下操作:
 Workbook book  =  Workbook.getWorkbook( new  File( " 测试1.xls " ));
         //  获得第一个工作表对象 
         Sheet sheet  =  book.getSheet( 0 );
         //  得到第一列第一行的单元格 
          int  columnum  =  sheet.getColumns(); //  得到列数 
          int  rownum  =  sheet.getRows(); //  得到行数 
         System.out.println(columnum);
        System.out.println(rownum);
         for  ( int  i  =   0 ; i  <  rownum; i ++ ) //  循环进行读写 
            {
             for  ( int  j  =   0 ; j  <  columnum; j ++ )   {
                Cell cell1  =  sheet.getCell(j, i);
                String result  =  cell1.getContents();
                System.out.print(result);
                System.out.print( " \t " );
            } 
            System.out.println();
        } 
        book.close(); 
       
   发表时间:2006-10-09  
ExcelBean.java文件用于生成Excel

public class ExcelBean {

    public String expordExcel(OutputStream os, List courseList,List studentList)
            throws Exception {

        WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
        String tmptitle = "课程“"+((Course_info)courseList.get(0)).getCource_name()+"”的选课学生列表"; // 标题
        WritableSheet wsheet = wbook.createSheet("第一页", 0); // sheet名称
        // 设置excel标题
        WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,
                WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
                Colour.BLACK);
        WritableCellFormat wcfFC = new WritableCellFormat(wfont);
        wsheet.addCell(new Label(1, 0, tmptitle, wcfFC));
        wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,
                WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
                Colour.BLACK);
        wcfFC = new WritableCellFormat(wfont);
        // 开始生成主体内容                
        wsheet.addCell(new Label(0, 2, "课程名称"));
        wsheet.addCell(new Label(1, 2, "学 号"));
       .........
        for(int i=3;i<studentList.size()+3;i++)
        {
            wsheet.addCell(new Label(0, i, ((Course_info)courseList.get(0)).getCource_name()));
            wsheet.addCell(new Label(1, i, ((Student_info)studentList.get(0)).getStudentID()));
      ...........
        }        
        // 主体内容生成结束        
        wbook.write(); // 写入文件
        wbook.close();
        os.close();
        return "success";
    }
}


控制器:

public class EExcelDownController extends AbstractController {
    
    private ICourse_infoManage courseManage;

    public void setCourseManage(ICourse_infoManage courseManage) {
        this.courseManage = courseManage;
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {    
        Integer course_id=new Integer(request.getParameter("course_id"));
        List courseList=this.courseManage.getCourseById(course_id);        
        List studentList = this.courseManage.getStudentByCourseId(course_id);
         try {    
            OutputStream os = response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            response.setHeader("Content-disposition", "attachment; filename=student.xls");// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            ExcelBean excelBean = new ExcelBean();
            excelBean.expordExcel(os,courseList,studentList);// 调用生成excel文件bean
        } catch (Exception e) {
            System.out.println(e);
        }            
        return null;    
    }
}
1 请登录后投票
   发表时间:2006-10-09  
将Excel文件内容写入到数据库
  public   class  EStudentInsertExcelController  extends  SimpleFormController   {

     private  IStudent_infoManage studentManage;

    @Override
     protected  ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
             throws  Exception   {
        Student_info student_info  =  (Student_info) command;
         try    {            
            MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;
            MultipartFile file  =  multipartRequest.getFile( " Excelfile " );  //  获得文件: 
             File toFile  =   new  File( " c:\\学生信息临时文件.xls " ); //  产生文件名和空文件 
             file.transferTo(toFile); //  文件上传 
             Workbook book  =  Workbook.getWorkbook(toFile); // 得到工作薄             
             Sheet sheet  =  book.getSheet( 0 ); //  获得第一个工作表对象 
              int  row  =  sheet.getRows(); //  /得到该sheet的行数 
              int  column  =  sheet.getColumns();  //  得到该sheet的列数     
             System.out.println( " 数据行数= " + row);
            System.out.println( " 数据列数= " + column);
             for ( int  i = 1 ;i < row;i ++ )
              {
                 for ( int  j = 0 ;j < column;j ++ )
                  {
                    System.out.println( " j= " + j);
                    sheet.getCell(j, i).getContents(); //  得到第j列第i行的单元格的类容         
                     student_info.setStudentID(sheet.getCell(j, i).getContents());    
                   ........................  
                }     
                 if  ( this .studentManage.getStudentByStudentID(
                        student_info.getStudentID()).size()  !=   0 )
                     return   new  ModelAndView( " education/e-studentInfoAddError " );
                 this .studentManage.insertStudent_info(student_info);    
            }                 
            book.close();
             return   new  ModelAndView( " education/e-studentInfoAddExcelSuccess " , " row " , new  Integer(row - 1 ));
        }   catch  (Exception e)   {                    
            e.printStackTrace();
        } 
         return   new  ModelAndView( " education/e-studentInfoAddExcelError " );
    } 
 
      public   void  setStudentManage(IStudent_infoManage studentManage)   {
         this .studentManage  =  studentManage;
    }     
} 
0 请登录后投票
   发表时间:2006-10-09  
spring 生成Excel和PDF文件
HTML页面并不总是向用户显示数据输出的最好方式,有时候需要生成不可改变的文件打印,PDF可能是种不错的选择。

Spring支持从数据动态生成PDF或Excel文件

下面这个简单实现的例子实现了spring输出PDF和Excel文件,为了使用Excel电子表格,你需要在你的classpath中加入poi-2.5.1.jar库文件,而对PDF文件,则需要iText.jar文件。它们都包含在Spring的主发布包中。

下面是测试项目代码:


1、控制器配置代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <bean id="beanNameViewResolver"
        class="org.springframework.web.servlet.view.BeanNameViewResolver" />

    <bean id="viewController" class="com.zhupan.spring.ViewController" />
    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/view*.shtml">viewController</prop>
            </props>
        </property>
    </bean>
</beans>

3、用于Excel视图的视图子类化
为了在生成输出文档的过程中实现定制的行为,我们将继承合适的抽象类。对于Excel,这包括提供一个 org.springframework.web.servlet.view.document.AbstractExcelView的子类,并实现 buildExcelDocument方法。
public class ViewExcel extends AbstractExcelView {

  public void buildExcelDocument(
             Map model, HSSFWorkbook workbook,
             HttpServletRequest request, HttpServletResponse response)
    throws Exception {
  
       HSSFSheet sheet = workbook.createSheet("list");
       sheet.setDefaultColumnWidth((short) 12);
       
       
       HSSFCell cell = getCell(sheet, 0, 0);
       setText(cell, "Spring Excel test");
  
       HSSFCellStyle dateStyle = workbook.createCellStyle();
       dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
       cell = getCell(sheet, 1, 0);
       cell.setCellValue(new Date());
       cell.setCellStyle(dateStyle);
       getCell(sheet, 2, 0).setCellValue(458);
  
       HSSFRow sheetRow = sheet.createRow(3);
       for (short i = 0; i < 10; i++) {
             sheetRow.createCell(i).setCellValue(i * 10);
       }

  }
  
}

4、用于PDF视图的视图子类化
需要象下面一样继承org.springframework.web.servlet.view.document.AbstractPdfView,并实现buildPdfDocument()方法。
public class ViewPDF extends AbstractPdfView {
    public void buildPdfDocument(Map model, Document document,
            PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        List list = (List) model.get("list");

        for (int i = 0; i < list.size(); i++)
            document.add(new Paragraph((String) list.get(i)));
    }

}

5、其他文件
1)控制器ViewController
public class ViewController extends MultiActionController{
     
     public ModelAndView viewPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
       List list = new ArrayList();
       Map model=new HashMap();
       list.add("test1");
       list.add("test2");
       model.put("list",list);
       ViewPDF viewPDF=new ViewPDF();
       return new ModelAndView(viewPDF,model);
  }
     
      public ModelAndView viewExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
            List list = new ArrayList();
        Map model=new HashMap();
        list.add("test1");
        list.add("test2");
        model.put("list",list);
        ViewExcel viewExcel=new ViewExcel();
        return new ModelAndView(viewExcel,model);
      }
}


2)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>springPDFTest</display-name>
    <servlet>
        <servlet-name>springPDFTest</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springPDFTest</servlet-name>
        <url-pattern>*.shtml</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

3)index.jsp
<%@ page contentType="text/html; charset=gb2312"%>

<a href="viewPDF.shtml">PDF视图打开 </a>
<br>
<a href="viewExcel.shtml">Excel视图打开</a>
0 请登录后投票
   发表时间:2006-10-09  
网页链接到Excel打开时乱码解决办法:

问题:

 < a   href ="excel/test.xls" > 打开 </ a >        【乱码】   


解决方法:

web.xml里加上 :
 < mime-mapping > 
         < extension > xls </ extension > 
         < mime-type > application/vnd.ms-excel </ mime-type > 
     </ mime-mapping > 


让他下载然后直接打开即可
1 请登录后投票
   发表时间:2006-10-16  
thanks
0 请登录后投票
   发表时间:2006-10-16  
spring的好用,省的自己写factoryBean
0 请登录后投票
   发表时间:2006-10-16  
楼主弄错了,jxl的作者是一位英国人吧?
这是他的邮箱。我和他交流过。
andyk@andykhan.freeserve.co.uk
0 请登录后投票
   发表时间:2006-10-16  
jarkarta的poi也好用的,且读取性能不错
1 请登录后投票
   发表时间:2006-10-16  
我们当时有个项目需要读写excel文件,所以稍微研究了一下这两个开源的组件,结果是poi对formula的支持不是很理想,对日期支持也有限(不过可以自定义类实现对日期的支持)。请问楼主有没有对jexcel和poi做全面的评估对比?
1 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics