导出数据库数据到Excel

做了一个利用POI导出数据库数据到Excel的例子,并把这个例子与大家一起分享,一起学习,共同进步!
先简单介绍一下poi,poi是apache组织的一个开源项目,最新版为poi-3.0.1,要使用poi需要到apache网站下载poi-bin3.0.1.zip压缩包,并将poi-3.0.1.jar加入到项目的ClassPath中。

下面是完成这个实例的步骤:

1、建立好一个web工程:poi;

2、导入所需要的jar包:poi-3.0.1.jar和mysql数据库驱动包;

3、编写一个StudentResultSet类,用于取出数据库中的数据;

Java代码
  1. packageorg.hnylj.poi;
  2. importjava.sql.Connection;
  3. importjava.sql.DriverManager;
  4. importjava.sql.PreparedStatement;
  5. importjava.sql.ResultSet;
  6. importjava.sql.SQLException;
  7. publicclassStudentResultSet{
  8. privateConnectionconn;
  9. privatePreparedStatementpstmt;
  10. privateResultSetrs;
  11. privatestaticfinalStringDRIVER="com.mysql.jdbc.Driver";
  12. privatestaticfinalStringURL="jdbc:mysql://localhost:3306/poi";
  13. privatestaticfinalStringUSERNAME="root";
  14. privatestaticfinalStringPASSWORD="123";
  15. //查询数据库中的数据
  16. publicResultSetquery(){
  17. try{
  18. Class.forName(DRIVER);
  19. conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
  20. pstmt=conn.prepareStatement("select*fromstudent");
  21. rs=pstmt.executeQuery();
  22. }catch(ClassNotFoundExceptione){
  23. e.printStackTrace();
  24. }catch(SQLExceptione){
  25. e.printStackTrace();
  26. }
  27. returnrs;
  28. }
  29. }

4、编写一个BuildExcelServlet,用于生成Excel;

Java代码
  1. packageorg.hnylj.poi;
  2. importjava.io.FileOutputStream;
  3. importjava.io.IOException;
  4. importjava.sql.ResultSet;
  5. importjava.sql.ResultSetMetaData;
  6. importjavax.servlet.ServletException;
  7. importjavax.servlet.http.HttpServlet;
  8. importjavax.servlet.http.HttpServletRequest;
  9. importjavax.servlet.http.HttpServletResponse;
  10. importorg.apache.poi.hssf.usermodel.HSSFCell;
  11. importorg.apache.poi.hssf.usermodel.HSSFRichTextString;
  12. importorg.apache.poi.hssf.usermodel.HSSFRow;
  13. importorg.apache.poi.hssf.usermodel.HSSFSheet;
  14. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
  15. publicclassBuildExcelServletextendsHttpServlet{
  16. protectedvoiddoGet(HttpServletRequestrequest,
  17. HttpServletResponseresponse)throwsServletException,IOException{
  18. StudentResultSetstuResultSet=newStudentResultSet();
  19. ResultSetrs=stuResultSet.query();
  20. StringxlsName="test.xls";
  21. StringsheetName="sheetName";
  22. HSSFWorkbookworkbook=newHSSFWorkbook();
  23. HSSFSheetsheet=workbook.createSheet();
  24. workbook.setSheetName(0,sheetName);
  25. HSSFRowrow=sheet.createRow((short)0);
  26. HSSFCellcell;
  27. try{
  28. ResultSetMetaDatamd=rs.getMetaData();
  29. intnColumn=md.getColumnCount();
  30. for(inti=1;i<=nColumn;i++){
  31. cell=row.createCell((short)(i-1));
  32. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  33. cell.setCellValue(newHSSFRichTextString(md.getColumnLabel(i)));
  34. }
  35. intiRow=1;
  36. while(rs.next()){
  37. row=sheet.createRow((short)iRow);
  38. ;
  39. for(intj=1;j<=nColumn;j++){
  40. cell=row.createCell((short)(j-1));
  41. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  42. cell.setCellValue(newHSSFRichTextString(rs.getObject(j)
  43. .toString()));
  44. }
  45. iRow++;
  46. }
  47. Stringfilename=request.getRealPath("/")+xlsName;
  48. request.setAttribute("filename",filename);
  49. FileOutputStreamfOut=newFileOutputStream(filename);
  50. workbook.write(fOut);
  51. fOut.flush();
  52. fOut.close();
  53. request.getRequestDispatcher("OpenExcelServlet").forward(request,
  54. response);
  55. }catch(Exceptione){
  56. e.printStackTrace();
  57. }
  58. }
  59. protectedvoiddoPost(HttpServletRequestrequest,
  60. HttpServletResponseresponse)throwsServletException,IOException{
  61. this.doGet(request,response);
  62. }
  63. }

5、编写一个OpenExcelServlet,用于把生成的Excel在页面上打开;

Java代码
  1. packageorg.hnylj.poi;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.FileInputStream;
  4. importjava.io.IOException;
  5. importjava.io.PrintWriter;
  6. importjavax.servlet.ServletException;
  7. importjavax.servlet.http.HttpServlet;
  8. importjavax.servlet.http.HttpServletRequest;
  9. importjavax.servlet.http.HttpServletResponse;
  10. publicclassOpenExcelServletextendsHttpServlet{
  11. publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
  12. throwsServletException,IOException{
  13. response.setContentType("application/vnd.ms-excel");
  14. PrintWriterout=response.getWriter();
  15. StringfilePath=(String)request.getAttribute("filename");
  16. BufferedInputStreambis=null;
  17. try{
  18. bis=newBufferedInputStream(newFileInputStream(filePath));
  19. intbytesRead;
  20. while((bytesRead=bis.read())!=-1){
  21. out.write(bytesRead);
  22. out.flush();
  23. }
  24. }catch(IOExceptione){
  25. e.printStackTrace();
  26. }finally{
  27. if(bis!=null)
  28. bis.close();
  29. if(out!=null)
  30. out.close();
  31. }
  32. }
  33. publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
  34. throwsServletException,IOException{
  35. this.doGet(request,response);
  36. }
  37. }

6、在web.xml里配置一下servlet的映射;

Xml代码
  1. <servlet>
  2. <servlet-name>BuildExcelServlet</servlet-name>
  3. <servlet-class>org.hnylj.poi.BuildExcelServlet</servlet-class>
  4. </servlet>
  5. <servlet>
  6. <servlet-name>OpenExcelServlet</servlet-name>
  7. <servlet-class>org.hnylj.poi.OpenExcelServlet</servlet-class>
  8. </servlet>
  9. <servlet-mapping>
  10. <servlet-name>OpenExcelServlet</servlet-name>
  11. <url-pattern>/OpenExcelServlet</url-pattern>
  12. </servlet-mapping>
  13. <servlet-mapping>
  14. <servlet-name>BuildExcelServlet</servlet-name>
  15. <url-pattern>/BuildExcelServlet</url-pattern>
  16. </servlet-mapping>

7、启动tomcat,运行程序

你可能感兴趣的:(Excel)