java操作Excel文件

JAVA操作Excel:

(1)数据库连接类:

package com.together.nms.dt.data.model.hibernate.db;

import java.sql.*;

public class SheetDataSource {

 private static Connection con;

 @SuppressWarnings("unused")
 private static final String DatabaseName = "uchome";

 private static final String userName = "root";

 private static final String password = "root";

 public SheetDataSource() {
  try {
   Class.forName("com.mysql.jdbc.Driver");
   try {
    con = DriverManager
      .getConnection(
        "jdbc:mysql://localhost:3306/uchome?characterEncoding=gbk",
        userName, password);
   } catch (SQLException e) {
    e.printStackTrace();
   }
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }

 public static ResultSet selectAllDataFromDB() throws SQLException {
  new SheetDataSource();
  Statement stmt = con.createStatement();
  return stmt.executeQuery("select * from shop_right");
 }
}

 

(2)操作Excel文件的核心类:

/**
 *  程序功能:将数据库表导入到Excel中
 *  做成日期:2011-07-01
 */
package com.together.nms.dt.data.model.hibernate.dao;

import java.beans.Statement;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFooter;
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;

import com.landmass.nms.data.model.common.db.ConnectionManager;
import com.together.nms.dt.data.model.hibernate.db.SheetDataSource;

public class ExportExcel {
 // 连接对象
 Connection conn = null;
 // 执行sql语句对象
 Statement stmtStatement = null;
 // 数据集对象
 ResultSet rsResultSet = null;

 // 初始化构造函数
 public ExportExcel() {
 }

 // 创建表头
 public static final String[] tableHeader = { "权限ID", "SHOP_RLEARNINGSTAGE",
   "SHOP_RLEARNINGSTAGEID", "SHOP_RGRADE", "SHOP_RGRADEID",
   "SHOP_RSUBJECT", "SHOP_RSUBJECTID", "SHOP_REDITION",
   "SHOP_REDITIONID", "SHOP_RDIFFERENCE", "SHOP_RDIFFERENCEID",
   "SHOP_MUPATEEDITIONDATE", "SHOP_MUPATEEDITIONDATEID", "SHOP_BOOKID" };

 // 创建工作薄
 public static HSSFWorkbook demoWorkBook = new HSSFWorkbook();

 // 创建表
 public static HSSFSheet demoSheet = demoWorkBook.createSheet("权限表");

 // 表头的单元格个数目
 public static final short cellNumber = (short) tableHeader.length;

 // 数据库表的列数
 public static final int columNumber = 14;

 /**
  * 创建表头
  */
 public static void createTableHeader() {

  HSSFHeader header = demoSheet.getHeader();
  header.setCenter("权限表");
  HSSFRow headerRow = demoSheet.createRow((short) 0);
  for (int i = 0; i < cellNumber; i++) {
   HSSFCell headerCell = headerRow.createCell((short) i);
   headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
   headerCell.setCellValue(tableHeader[i]);
  }
 }

 // 创建行
 public static void createTableRow(List<String> cells, short rowIndex) {

  // 创建第rowIndex行
  HSSFRow row = demoSheet.createRow((short) rowIndex);
  for (short i = 0; i < cells.size(); i++) {
   // 创建第i个单元格
   HSSFCell cell = row.createCell((short) i);
   cell.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell.setCellValue(cells.get(i));
  }
 }

 // 创建整个Excel表格
 @SuppressWarnings("unused")
 public static void createExcelSheeet() throws SQLException {

  createTableHeader(); // 创建表头
  ConnectionManager conn = new ConnectionManager();
  ResultSet rs = SheetDataSource.selectAllDataFromDB(); // 取得数据库连接
  int rowIndex = 1;
  while (rs.next()) {
   List<String> list = new ArrayList<String>();
   for (int i = 1; i <= columNumber; i++) {
    list.add(rs.getString(i));
   }
   createTableRow(list, (short) rowIndex);
   rowIndex++;
  }
 }

 // 导出表格
 public void exportExcel(HSSFSheet sheet, OutputStream os)
   throws IOException {
  sheet.setGridsPrinted(true);
  HSSFFooter footer = sheet.getFooter();
  footer.setRight("Page " + HSSFFooter.page() + " of "
    + HSSFFooter.numPages());
  demoWorkBook.write(os);
 }

 // 测试主函数
 @SuppressWarnings("static-access")
 public static void main(String[] args) {
  // 定义excel名称
  String fileName = "D:\\shop_right.xls";
  // 文件输出流
  FileOutputStream fos = null;
  try {
   ExportExcel pd = new ExportExcel();
   pd.createExcelSheeet();
   fos = new FileOutputStream(fileName);
   pd.exportExcel(demoSheet, fos);
   JOptionPane.showMessageDialog(null, "EXCEL表格已成功导出到 : " + fileName);
  } catch (Exception e) {
   JOptionPane.showMessageDialog(null, "EXCEL表格导出出错,错误信息 :" + e
     + "\n错误原因可能是表格已经打开。");
   e.printStackTrace();
  } finally {
   try {
    fos.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
}

这里使用的是Apathe的poi对excel进行操作.

你可能感兴趣的:(Excel)