Java操作Excel文件的写入(文件中含有多张工作表)

在本人工作的过程中,遇到了形形色色的问题。当时琢磨了好久才琢磨出这样的总结,贴出来供大家参考参考。以下观点仅代表本人在工作过程中的观点,望大家能够共同讨论,查漏补缺。



由于工作需要,最近公司需要我来通过从数据库中导出表中的数据,然后将数据导出成Excel表格的性格。由于需要作出不同统计的操作,但是却要求导出成一个Excel文档,而不是多个文档。而在网上形形色色的资料中,似乎还没有找到一个Excel文档中导出多张工作表。因此,将我自己写的贴出来让大家参考参考。



首先我们来明确一下需求(表名以及表结构为虚构,大家需要针对自己的需求进行修改):

1、导出Employee表中的数据,其中Employee表中的数据格式为:
    Long id
    String username;
    int sex
    int age 
    String height
    String weight
    String ts (入职时间)

2、在一个Excel文档中需要统计出两种数据。一种为全部Employee的数据。一种为入职时间在本周的数据

所谓代码未动,jar包先行。我们首先需要的就是导入我们的jar包。
传送门:http://download.csdn.net/detail/a2279860a/9791283
注意:在这里我只提供apache的poi包,就是用于Java操作Excel的所需包,而不提供连接数据库的jar包。因此切勿忘记导入jar包时操作数据库需要导入相关的jar包

那么导入了jar包之后,我们就可以开始写我们的代码了!

首先我们需要定义一个UserinfoData类,用于封装查询到的数据

public class UserinfoData {
    
    private String email;
    private int sex;
    private String age;
    private String height;
    private String weight;
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getHeight() {
        return height;
    }
    public void setHeight(String height) {
        this.height = height;
    }
    public String getWeight() {
        return weight;
    }
    public void setWeight(String weight) {
        this.weight = weight;
    }
    
}               

这里可能就会有人疑惑了,Student表中不是有一个ts字段吗,怎么定义的UserinfoData中没有ts呢?
其实很简单啊,因为这样简单的操作不需要使用到框架那么高大上复杂的东西,使用简单的jdbc就行了,因此不必字段跟表中列相对应的。



创建好了封装对象之后,我们就需要通过查询数据库获取到相应的数据了。

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;

/**
 * 导出数据库中的数据到Excel中
 * @author 昆仑山神
 *
 */
 public class ExportExcelTest_poi {
    
    @Test
    public void testExcelExport() throws Exception {
        String DRIVER = "com.mysql.jdbc.Driver";  
        String URL = "jdbc:mysql:///test?useUnicode=true&characterEncoding=UTF-8";  
        String USERNAME = "xxxx";  
        String USERPASSWORD = "xxxx";   
        
        List oneWeek = DateUtil.getOneWeek();// 获取一周时间
    
        String sqlAll = "SELECT * FROM t_userinfo"; // 查询总用户数据  
        String sqlWeek = "SELECT * FROM t_userinfo WHERE ts BETWEEN '"+oneWeek.get(0)+"' AND '"+oneWeek.get(6)+ "'"; // 查询本周新增用户数据  

        
        // 连接数据库  
        Class.forName(DRIVER);  
        //声明对象
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        PreparedStatement psWeek = null;
        ResultSet rsWeek = null;
        
        try {
            conn = (Connection) DriverManager.getConnection(URL,USERNAME,USERPASSWORD);  
            ps = (PreparedStatement) conn.prepareStatement(sqlAll);  
            rs = (ResultSet) ps.executeQuery();  
            
            List userinfoDataList = new ArrayList();
            
            while(rs.next()){
                
                UserinfoData userinfoData = new UserinfoData();
                userinfoData.setEmail(rs.getString("username"));
                userinfoData.setSex(rs.getInt("sexCode"));
                userinfoData.setAge(rs.getString("birthday"));
                userinfoData.setHeight(rs.getString("height"));
                userinfoData.setWeight(rs.getString("weight"));
                
                userinfoDataList.add(userinfoData);
            }
            
            System.out.println(userinfoDataList.size());
            
            
            psWeek = (PreparedStatement) conn.prepareStatement(sqlWeek);  
            rsWeek = (ResultSet) psWeek.executeQuery();  
            
            List userinfoDataListWeek = new ArrayList();
            
            while(rsWeek.next()){
                
                UserinfoData userinfoData = new UserinfoData();
                userinfoData.setEmail(rsWeek.getString("username"));
                userinfoData.setSex(rsWeek.getInt("sexCode"));
                userinfoData.setAge(rsWeek.getString("birthday"));
                userinfoData.setHeight(rsWeek.getString("height"));
                userinfoData.setWeight(rsWeek.getString("weight"));
                
                userinfoDataListWeek.add(userinfoData);
            }
            
            System.out.println(userinfoDataListWeek.size());
            
            // 导出文件  
            CreateExcelUtil.createExcel(userinfoDataList, userinfoDataListWeek);
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //关闭连接
            try {
                if(rs != null){
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }finally{
                try {
                    if(ps != null){
                        ps.close();
                    }
                } catch (Exception e3) {
                    e3.printStackTrace();
                }finally{
                    try {
                        if(conn != null){
                            conn.close();
                        }
                    } catch (Exception e4) {
                        e4.printStackTrace();
                    }
                }
            }
            
        }
    }
}   

因为我们需要获取到本周的数据,因此需要对时间进行解析,因此我们额外的写了一个工具类。

                
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DateUtil {
    
    
    private static final int FIRST_DAY = Calendar.MONDAY;
    
    
    public static List getOneWeek(){
        
        List weekList = new ArrayList();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        Calendar calendar = Calendar.getInstance();
        setToFirstDay(calendar);
        for (int i = 0; i < 7; i++) {
            if(i == 0){
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
            }else if(i == 6){
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
            }
            
            
            weekList.add(dateFormat.format(calendar.getTime()));
            
            calendar.add(Calendar.DATE, 1);
        }
        return weekList;
        
    }
    
     private static void setToFirstDay(Calendar calendar) {
        while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
            calendar.add(Calendar.DATE, -1);
        }
    }   
}               

最后的重头戏就是我们的生成文件的程序了:

import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 导出数据库中的数据到Excel中
 * @author 昆仑山神
 *
 */
@SuppressWarnings("deprecation")
public class CreateSimpleExcelToDisk  
{  
   
    public static boolean createExcel(List userinfoDataListAll, List userinfoDataListWeek) throws Exception{ 
        
        try {
            if(userinfoDataListAll != null && userinfoDataListAll.size() > 0){
                
                
                // 创建一个webbook,对应一个Excel文件  
                HSSFWorkbook wb = new HSSFWorkbook();  
                
                // 在webbook中添加多个sheet,对应Excel文件中的sheet  
                HSSFSheet sheetAll = wb.createSheet("总用户表");
                
                // 设置格式,设置表头居中  
                HSSFCellStyle style = wb.createCellStyle();  
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  

                // 在sheet中添加表头第0行,显示总用户数 
                HSSFRow rowAllHead = sheetAll.createRow((int) 0); 
                HSSFCell cellAllHead = rowAllHead.createCell((short) 0);
                cellAllHead.setCellValue("总用户数:  " + userinfoDataListAll.size());  
                cellAllHead.setCellStyle(style);  
                        
                //总用户表
                HSSFRow rowAll = sheetAll.createRow((int) 1); 
                HSSFCell cellAll = rowAll.createCell((short) 0);  
                //设置列名以及格式(与传入的List集合中的对象的字段相一致)
                cellAll.setCellValue("邮箱");  
                cellAll.setCellStyle(style);  
                cellAll = rowAll.createCell((short) 1);  
                cellAll.setCellValue("性别");  
                cellAll.setCellStyle(style);  
                cellAll = rowAll.createCell((short) 2);  
                cellAll.setCellValue("年龄");  
                cellAll.setCellStyle(style);  
                cellAll = rowAll.createCell((short) 3);  
                cellAll.setCellValue("身高");  
                cellAll.setCellStyle(style);  
                cellAll = rowAll.createCell((short) 4);  
                cellAll.setCellValue("体重");  
                cellAll.setCellStyle(style); 
                
                // 写入实体数据  
                for (int i = 0; i < userinfoDataListAll.size(); i++)  
                {  
                    rowAll = sheetAll.createRow((int) i + 2);  
                    UserinfoData ud = (UserinfoData) userinfoDataListAll.get(i);  
                    // 创建单元格,并设置值  
                    rowAll.createCell((short) 0).setCellValue(ud.getEmail());  
                    rowAll.createCell((short) 1).setCellValue(ud.getSex() == 1 ? "男" : "女");  
                    rowAll.createCell((short) 2).setCellValue(ud.getAge());  
                    rowAll.createCell((short) 3).setCellValue(ud.getHeight());  
                    rowAll.createCell((short) 4).setCellValue(ud.getWeight());  
                }  
                //自动调整总用户表列宽
                sheetAll.autoSizeColumn((short)0); 
                sheetAll.autoSizeColumn((short)1); 
                sheetAll.autoSizeColumn((short)2); 
                sheetAll.autoSizeColumn((short)3); 
                sheetAll.autoSizeColumn((short)4); 
                
                //本周新增用户表
                
                HSSFSheet sheetWeek = wb.createSheet("本周新增用户表");  
                
             // 在sheet中添加表头第0行,显示本周增加用户数 
                HSSFRow rowWeekHead = sheetWeek.createRow((int) 0); 
                HSSFCell cellWeekHead = rowWeekHead.createCell((short) 0);
                cellWeekHead.setCellValue("本周新增用户数:  " + userinfoDataListWeek.size());  
                cellWeekHead.setCellStyle(style);  
                
                HSSFRow rowWeek = sheetWeek.createRow((int) 1);  
                HSSFCell cellWeek = rowWeek.createCell((short) 0);  
                //设置列名以及格式(与传入的List集合中的对象的字段相一致)
                cellWeek.setCellValue("邮箱");  
                cellWeek.setCellStyle(style);  
                cellWeek = rowWeek.createCell((short) 1);  
                cellWeek.setCellValue("性别");  
                cellWeek.setCellStyle(style);  
                cellWeek = rowWeek.createCell((short) 2);  
                cellWeek.setCellValue("年龄");  
                cellWeek.setCellStyle(style);  
                cellWeek = rowWeek.createCell((short) 3);  
                cellWeek.setCellValue("身高");  
                cellWeek.setCellStyle(style);  
                cellWeek = rowWeek.createCell((short) 4);  
                cellWeek.setCellValue("体重");  
                cellWeek.setCellStyle(style); 
                if(userinfoDataListWeek != null && userinfoDataListWeek.size() > 0){
                    // 写入实体数据
                    for (int i = 0; i < userinfoDataListWeek.size(); i++)  
                    {  
                        rowWeek = sheetWeek.createRow((int) i + 2);  
                        UserinfoData ud = (UserinfoData) userinfoDataListWeek.get(i);  
                        // 创建单元格,并设置值  
                        rowWeek.createCell((short) 0).setCellValue(ud.getEmail());  
                        rowWeek.createCell((short) 1).setCellValue(ud.getSex() == 1 ? "男" : "女");  
                        rowWeek.createCell((short) 2).setCellValue(ud.getAge());  
                        rowWeek.createCell((short) 3).setCellValue(ud.getHeight());  
                        rowWeek.createCell((short) 4).setCellValue(ud.getWeight());  
                    }  
                    
                }
                //自动调整本周新增用户表列宽
                sheetWeek.autoSizeColumn((short)0); 
                sheetWeek.autoSizeColumn((short)1); 
                sheetWeek.autoSizeColumn((short)2); 
                sheetWeek.autoSizeColumn((short)3); 
                sheetWeek.autoSizeColumn((short)4); 
                
                
             // 将文件存到指定位置  
                FileOutputStream fout = new FileOutputStream("E:/test.xls");  
                wb.write(fout);  
                fout.close();  
                
                return true;
                
            }else{
                return false;
            }
            
        } catch (Exception e) {
            e.printStackTrace();  
            return false;
        }
    }  
}

这样,我们就能够导出相关的数据出来啦!!导出来的文件大致样子是这样滴!

这里写图片描述

这里写图片描述

如果大家还有什么更加简便的方式,欢迎大家在评论区留言!

你可能感兴趣的:(Java操作Excel文件的写入(文件中含有多张工作表))