免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1837 | 回复: 0
打印 上一主题 下一主题

poi使用心得与写好的模块 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-01-09 08:59 |只看该作者 |倒序浏览
excel,一个电子表格。如今用户不在满足于网页上显示表格的形式,一些数据(例如财务方面)需要直接保存为excel表格。华表虽然好但是价格在那,
再说了,一个有追求的程序员是不可能没有自己的理想的,所以我选择了poi。一个开源的项目,但是我还 不算一个优秀的程序员
  1. package org.yzq;
  2. import java.util.LinkedList;
  3. public class ExcelBean
  4. {
  5.     private LinkedList listData = new LinkedList();
  6.    
  7.     public void setListData(LinkedList listData)
  8.     {
  9.         this.listData = listData;
  10.     }
  11.    
  12.     public void setListData(String[] strListData)
  13.     {
  14.         this.listData.add(strListData);
  15.     }
  16.    
  17.     public LinkedList getListData()
  18.     {
  19.         return listData;
  20.     }
  21. }
复制代码
  1. package org.yzq;
  2. import org.apache.poi.hssf.usermodel.*;
  3. import java.io.*;
  4. import java.util.*;
  5. import java.sql.*;
  6. public class ExcelCreate
  7. {
  8.     private ResultSet rs = null;
  9.     private Connection con = null;
  10.     private Statement stmt = null;
  11.     FileOutputStream file = null;
  12.     private String excelFile = "d:\poi\friends.xls";
  13.    
  14.     private void createExcel()
  15.     {
  16.         try
  17.         {
  18.             ExcelBean eb = new ExcelBean();
  19.             Class.forName("org.gjt.mm.mysql.Driver").newInstance();
  20.             con =
  21. DriverManager.getConnection("jdbc:mysql://127.0.0.1/demo","yzq","8383055");
  22.             stmt = con.createStatement();
  23.             rs =
  24. stmt.executeQuery("select id,name,sex,age,mobile,address,memo from
  25. friends");
  26.             while(rs.next())
  27.             {
  28.            
  29.     eb.setListData(new
  30. String[]{(rs.getInt("id")+"").toString().trim(),rs.getString("name").toString().trim(),rs.getString("sex").toString().trim(),(rs.getInt("age")+"").toString().trim(),rs.getString("mobile").toString().trim(),rs.getString("address").toString().trim(),rs.getString("memo").toString().trim()});
  31.             }
  32.             String[] titleKeys = new String[]{"编号","姓名","性别","年龄","手机","地址","备注"};
  33.             LinkedList listData = eb.getListData();
  34.             HSSFWorkbook wb = new HSSFWorkbook();
  35.             HSSFSheet sheet = wb.createSheet("sheet0");
  36.             //sheet.setDefaultColumnWidth((short)100);
  37.             HSSFRow row = sheet.createRow((short)0);
  38.             for(int i=0;i<titleKeys.length;i++)
  39.             {
  40.                 HSSFCell cell = row.createCell((short)i);
  41.                 HSSFCellStyle cellStyle = wb.createCellStyle();
  42.                 HSSFFont cellFont = wb.createFont();
  43.                 cellFont.setBoldweight(cellFont.BOLDWEIGHT_BOLD);
  44.                 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  45.                 cellStyle.setFont(cellFont);
  46.                 cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  47.                 cell.setCellStyle(cellStyle);
  48.                 cell.setCellValue(titleKeys[i]);
  49.             }
  50.             for(int j=0;j<listData.size();j++)
  51.             {
  52.                 row = sheet.createRow((short)j+1);
  53.                 for(int k=0;k<titleKeys.length;k++)
  54.                 {
  55.            
  56.         HSSFCell cell =
  57. row.createCell((short)k);
  58.            
  59.         HSSFCellStyle cellStyle =
  60. wb.createCellStyle();
  61.            
  62.         HSSFFont cellFont =
  63. wb.createFont();
  64.            
  65.       
  66. cellFont.setColor(cellFont.COLOR_RED);
  67.                     cellStyle.setFont(cellFont);
  68.            
  69.       
  70. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  71.                     cell.setCellStyle(cellStyle);
  72.            
  73.         String[] list =
  74. (String[])listData.get(j);
  75.            
  76.       
  77. //sheet.setDefaultColumnWidth((short)list[k].length());
  78.                     cell.setCellValue(list[k]);
  79.                 }
  80.             }
  81.             file = new FileOutputStream(excelFile);
  82.             wb.write(file);
  83.             System.out.println("已成功生成excel文件");
  84.             
  85.         }
  86.         catch(Exception err)
  87.         {
  88.             err.printStackTrace();
  89.         }
  90.         finally
  91.         {
  92.             if(stmt != null)
  93.             {
  94.                 try
  95.                 {
  96.                     stmt.close();
  97.                     System.out.println("释放SQL句柄");
  98.                 }
  99.                 catch(Exception err)
  100.                 {
  101.                     err.printStackTrace();
  102.                 }
  103.             }
  104.             if(rs != null)
  105.             {
  106.                 try
  107.                 {
  108.                     rs.close();
  109.                     System.out.println("释放记录集");
  110.                 }
  111.                 catch(Exception err)
  112.                 {
  113.                     err.printStackTrace();
  114.                 }
  115.             }
  116.             if(con != null)
  117.             {
  118.                 try
  119.                 {
  120.                     con.close();
  121.                     System.out.println("释放连接");
  122.                 }
  123.                 catch(Exception err)
  124.                 {
  125.                     err.printStackTrace();
  126.                 }
  127.             }
  128.             if(file != null)
  129.             {
  130.                 try
  131.                 {
  132.                     file.close();
  133.                     System.out.println("关闭文件流");
  134.                 }
  135.                 catch(Exception err)
  136.                 {
  137.                     err.printStackTrace();
  138.                 }
  139.             }
  140.         }
  141.     }
  142.    
  143.     public static void main(String args[])
  144.     {
  145.         new ExcelCreate().createExcel();
  146.     }
  147. }
复制代码
  1. package org.yzq;
  2. import java.sql.*;
  3. import org.apache.poi.hssf.usermodel.*;
  4. import java.util.*;
  5. import java.io.*;
  6. public class ExcelToDatabase
  7. {
  8.     private Connection con = null;
  9.     private PreparedStatement pstmt = null;
  10.     private String excelFile = "d:\poi\friends.xls";
  11.    
  12.     private void insertDataFromExcel()
  13.     {
  14.         try
  15.         {
  16.             //ExcelBean eb = new ExcelBean();
  17.             String[] temp = new String[6];
  18.             HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(excelFile));
  19.             HSSFSheet sheet = wb.getSheet("sheet1");
  20.             Class.forName("org.gjt.mm.mysql.Driver").newInstance();
  21.             con =
  22. DriverManager.getConnection("jdbc:mysql://127.0.0.1/demo","yzq","8383055");
  23.             pstmt =
  24. con.prepareStatement("INSERT INTO
  25. friends(name,sex,age,mobile,address,memo) VALUES(?,?,?,?,?,?)");
  26.             //持久化数据
  27.             for(int i=0;i<=sheet.getLastRowNum();i++)
  28.             {
  29.                 ExcelBean eb = new ExcelBean();
  30.                 HSSFRow row = sheet.getRow(i);
  31.                 for(short j=0;j<row.getLastCellNum();j++)
  32.                 {
  33.                     HSSFCell cell = row.getCell(j);
  34.            
  35.       
  36. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  37.            
  38.         temp[j] =
  39. cell.getStringCellValue();
  40.                     //System.out.println(temp[j]);
  41.                 }
  42.                 eb.setListData(temp);
  43.                 //将数据插入到数据库中
  44.                 LinkedList listData = eb.getListData();
  45.                 for(int m=0;m<listData.size();m++)
  46.                 {
  47.                     for(int n=0;n<temp.length;n++)
  48.                     {
  49.            
  50.            
  51. System.out.print(temp[n]+"        ");
  52.                         if(n==2)
  53.                         {
  54.            
  55.            
  56.    
  57. pstmt.setInt(n+1,Integer.parseInt(temp[n].toString().trim()));
  58.                         }
  59.                         else
  60.                         {
  61.            
  62.            
  63.     pstmt.setString(n+1,temp[n].toString().trim());
  64.                         }
  65.                     }
  66.                     pstmt.execute();
  67.                     //System.out.println();
  68.            
  69.       
  70. /*pstmt.setString(1,temp[0].toString().trim());
  71.            
  72.       
  73. pstmt.setString(2,temp[1].toString().trim());
  74.            
  75.       
  76. pstmt.setInt(3,Integer.parseInt(temp[2].toString().trim()));
  77.            
  78.       
  79. pstmt.setString(4,temp[3].toString().trim());
  80.            
  81.       
  82. pstmt.setString(5,temp[4].toString().trim());
  83.            
  84.       
  85. pstmt.setString(6,temp[5].toString().trim());
  86.                     pstmt.execute();*/
  87.            
  88.       
  89. System.out.println("成功插入了"+(m+1)+"条");
  90.                 }
  91.             }
  92.         }
  93.         catch(Exception err)
  94.         {
  95.             err.printStackTrace();
  96.         }
  97.         finally
  98.         {
  99.             if(pstmt != null)
  100.             {
  101.                 try
  102.                 {
  103.                     pstmt.close();
  104.                 }
  105.                 catch(Exception err)
  106.                 {
  107.                     err.printStackTrace();
  108.                 }
  109.             }
  110.             if(con != null)
  111.             {
  112.                 try
  113.                 {
  114.                     con.close();
  115.                 }
  116.                 catch(Exception err)
  117.                 {
  118.                     err.printStackTrace();
  119.                 }
  120.             }
  121.         }
  122.     }
  123.    
  124.     public static void main(String args[])
  125.     {
  126.         new ExcelToDatabase().insertDataFromExcel();
  127.     }
  128. }
复制代码
  1. package org.yzq;
  2. import org.apache.poi.hssf.usermodel.*;
  3. import java.io.*;
  4. public class ReadExcel
  5. {
  6.     private String excelFile = "d:\poi\friends.xls";
  7.    
  8.     private void showExcel()
  9.     {
  10.         try
  11.         {
  12.             HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(excelFile));
  13.             HSSFSheet sheet = wb.getSheet("sheet0");
  14.             for(int i=0;i<sheet.getLastRowNum();i++)
  15.             {
  16.                 HSSFRow row = sheet.getRow(i);
  17.                 for(short j=0;j<row.getLastCellNum();j++)
  18.                 {
  19.                     HSSFCell cell = row.getCell(j);
  20.            
  21.       
  22. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  23.                     if((j==3)&&(i!=0))
  24.                     {
  25.            
  26.            
  27. System.out.print(cell.getNumericCellValue()+"        ");
  28.                     }
  29.                     else
  30.                     {
  31.            
  32.            
  33. System.out.print(cell.getStringCellValue()+"        ");
  34.                     }
  35.                 }
  36.                 System.out.println();
  37.             }
  38.         }
  39.         catch(Exception err)
  40.         {
  41.             err.printStackTrace();
  42.         }
  43.     }
  44.    
  45.     public static void main(String args[])
  46.     {
  47.         new ReadExcel().showExcel();
  48.     }
  49. }
复制代码
至于if(n==2)和if((j==3)&&(i!=0))是我当时一时没想到如何读取非String的数据而临时代替的,当然现在在真正的项目里就不这样写啦,呵呵
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/460/showart_66303.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP