将从数据库里读到的数据存入excel表格

1、首先要导入以下两个jar包
mysql-connector-java-5.1.41-bin.jar
poi-3.17.jar
2、通用类

public class WriteExcleUtil {
    public static List<String[]> write(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<String> setMethods = new ArrayList<>();
        ResultSetMetaData metaData;
        int columnCount = 0;
        List<String[]> list = new ArrayList<String[]>();
        // 获取数据
        try {
            conn = DBUtil.getConn();
            ps = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        }
        // 把列名放入集合
        try {
            metaData = rs.getMetaData();
            columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                setMethods.add(metaData.getColumnName(i));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 把数据放入集合
        try {
            while (rs.next()) {
                String[] str = new String[columnCount];
                for (int i = 0; i < columnCount; i++) {
                    List<String> string = setMethods;
                    Object empno = rs.getObject(setMethods.get(i).toString().toLowerCase());
                    str[i] = empno + "";
                }
                list.add(str);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for (String[] strings : list) {
            System.out.println(toString(strings));
        }

        // 创建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("sheet1");
        for (int row = 0; row < list.size() + 1; row++) {
            HSSFRow rows = sheet.createRow(row);
            // 向工作表中添加数据
            if (row == 0) {
                // 输出列名
                for (int col = 0; col < columnCount; col++) {
                    rows.createCell(col).setCellValue(setMethods.get(col).toString());
                }
            } else {
                // 输出数据
                String[] str1 = (String[]) list.get(row - 1);
                for (int col = 0; col < str1.length; col++) {
                    rows.createCell(col).setCellValue(str1[col]);
                }
            }
        }

        File xlsFile = new File("d:/poi1.xls");
        FileOutputStream xlsStream;
        try {
            xlsStream = new FileOutputStream(xlsFile);
            workbook.write(xlsStream);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DBUtil.close(conn, ps, rs);
        return list;
    }

    private static String toString(String[] a) {
         if (a == null)
                return "null";

            int iMax = a.length - 1;
            if (iMax == -1)
                return "";

            StringBuilder b = new StringBuilder();
            for (int i = 0; ; i++) {
                b.append(String.valueOf(a[i]));
                if (i == iMax)
                    return b.toString();
                b.append("\t ");
            }
    }
    //测试
    public static void main(String[] args) {
        String sql = "select * from employee";
        List<String[]> write = write( sql, null);
    }

}

3、工具类

public class DBUtil {

    private Connection conn;
    private Statement stat;
    private ResultSet rs;


    /**
     * 获取连接的方法
     * @throws SQLException 
     */
    public static Connection getConn() throws SQLException{
        InputStream input = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties p = new Properties();
        try {
            p.load(input);
            String dirver = p.getProperty("driver");
            Class.forName(dirver);
            String url = p.getProperty("url");
            String username = p.getProperty("username");
            String password = p.getProperty("password");
            return DriverManager.getConnection(url,username,password);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭流(增删改)
     */
    public static void close(Connection conn,Statement stat){
        if(stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭流:查询
     */
    public static void close(Connection conn,Statement stat,ResultSet rs){
        close(conn,stat);   
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Shawn_bean/article/details/82531460