java操作excel

  今天听朋友介绍,了解了POI, apache组织的一个开源项目,提供了对Microsoft excel,word 的纯java
解决方案, http://jakarta.apache.org/poi/  里面可以下载到开发包,还有例子程序,用起来还是很方便的!

下面是一个将Oracle数据库表导出为Excel的程序:

import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;      //单元格
import org.apache.poi.hssf.usermodel.HSSFCellStyle; //单元格样式
import org.apache.poi.hssf.usermodel.HSSFDataFormat;//数据格式
import org.apache.poi.hssf.usermodel.HSSFFont;      //字体
import org.apache.poi.hssf.usermodel.HSSFHeader;    //头  
import org.apache.poi.hssf.usermodel.HSSFRow;       //行
import org.apache.poi.hssf.usermodel.HSSFSheet;     //一张记事簿
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  //一个excel
import org.apache.poi.hssf.util.HSSFColor;          //颜色
import java.sql.*;


 

public class Test{
    
     public static void main(String[] args) throws  Exception
     {
       String filename = "dept.xls";
       String column_name="";
       PreparedStatement ps=null;  //预编译
       Connection conn=null;      //连接
       Statement smt=null;         //sql语句
       ResultSet rs = null,rs1=null;        //结果集合
       ResultSetMetaData md = null;         
      long rowCount =0l;               //总行数
        try{
      
        Class.forName("oracle.jdbc.driver.OracleDriver");
        }catch(Exception e){
         e.printStackTrace();
        }
        String url = "jdbc:oracle:thin:@172.18.2.114:1521:MIS";
        String userName = "scott";
        String password = "tiger";
        conn = DriverManager.getConnection (url, userName, password);
        smt = conn.createStatement();
       
        //取得总记录数
        String sql="select deptno,dname,loc from dept";
        String sqlqeury="select count(*) as total from (  "+sql+"  )";
        try{
             rs = smt.executeQuery(sqlqeury);
             if(rs.next()){
                 rowCount =rs.getLong("total");
                 System.out.print(rowCount) ; //记录总数
              }
          }catch(Exception e){
           System.out.print("aaa");
                 e.printStackTrace();
                 System.out.println(e.getMessage());
                 conn.close();   //异常后关闭连接
                 throw new Exception("获得记录总数失败");
           }
        
         //处理sql语句
         try{
              rs1 = smt.executeQuery(sql);
              md = rs1.getMetaData();
               System.out.print(md.getColumnCount());
          }catch(Exception e){
            System.out.print("bbb");
                e.printStackTrace();
                System.out.println(e.getMessage());
                conn.close();   //异常后关闭连接
                throw new Exception("传入的SQL无法处理");
         }
        
        
        //生成excel代码
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("new sheet");
        HSSFRow row = null;
        HSSFCell cell=null;
        for(long i =0;i<=rowCount;i++){
           
            row = sheet.createRow((short)i);                     //创建一个行
            for(int j =0;j<md.getColumnCount();j++){
             
               cell = row.createCell((short)j);                  //创建单元格
               cell.setEncoding(HSSFCell.ENCODING_UTF_16);
               if(i==0){   
                  cell.setCellValue(md.getColumnName(j+1));     //设定单元格的值
               }else{
                  cell.setCellValue(rs1.getString(j+1));        //设定单元格的值
                }
             }
             rs1.next();
         }
        //写到excel中!
        FileOutputStream fileOut = new FileOutputStream(filename);
        wb.write(fileOut);          //向fileout文件写
        fileOut.close();            //关闭文件输出流
        conn.close();               //关闭正常连接  
   }
  
}

 

                                                     2004.12.22   
                                                     ladofwind@163.com

部分代码.................. . .. .. /** * 处理动态表格 * 默认取第二行第一列的标识 * @param table * @param ctRow * @param values 需要添加的数据 */ public static void processDynamicTable(XWPFTable table, CTRow ctRow, List values) { if(values==null || values.size()==0) return; for (Iterator iterator = values.iterator(); iterator.hasNext();) { String[] value = iterator.next(); XWPFTableRow newRow = new XWPFTableRow(ctRow,table); List cells = newRow.getTableCells(); if(cells==null || cells.size()==0) return; for (int j = 0; j < cells.size(); j++) { XWPFTableCell cell = cells.get(j); cell.removeParagraph(0); if(j<=value.length) cell.setText(value[j]); } table.addRow(newRow); } } /** * 处理表格 * @param doc * @param dataMap */ public static void processTable(XWPFDocument doc, Map dataMap) { Iterator iter = doc.getTablesIterator(); while(iter.hasNext()) { XWPFTable table = iter.next(); List rows = table.getRows(); if(rows==null || rows.size()==0) continue; CTRow ctRow = null; for (int i = 0; i < rows.size(); i++) { XWPFTableRow row = rows.get(i); ctRow = (CTRow)row.getCtRow().copy(); List cells = row.getTableCells(); if(cells==null || cells.size()==0) continue; //处理标致 boolean sign = false; for (int j = 0; j < cells.size(); j++) { XWPFTableCell cell = cells.get(j); if(cell.getText()==null) continue; if(i==1 && j==0) { //取第二行第一列的值,再添加table.关键字之后与dataMap匹配,有则当动态表格处理 String key = "table."+ cell.getText(); if(dataMap.containsKey(key)) { List values = (List)dataMap.get(key); table.removeRow(1); processDynamicTable(table, ctRow, values); //更新处理标致 sign = true; break; } } if(!cell.getText().startsWith("\\$") && cell.getText().endsWith("\\$")) continue; String key = cell.getText().replaceAll("\\$", ""); if(dataMap.containsKey(key)) {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值