Java 动态数据导出不同格式excel表格(利用Apache POI导出Excel)

ps: 首先科普一下基础知识

 

  Excel 2003及以下的版本。一张表最大支持65536行数据,256列。也就是说excel2003完全不可能满足百万数据导出的需求。

  Excel 2007-2010版本。一张表最大支持1048576行,16384列;

 

HSSFWorkBook:操作2003版本以前的(包括2003版本),扩展名.xls,该类在org.apache.poi:poi中

XSSFWorkBook:操作2007版本以后的(包括2007版本),拓展名.xlsx,该类在org.apache.poi:poi-ooxml中

SXSSFWorkBook:对于海量的数据进行操作

第一种导出.xls表格:

利用Apache POI导出Excel。案例中使用的是list<对象>  需要用map自己改一下就好了!

1.ExportExcelUtil代码:

import java.io.OutputStream;  
import java.lang.reflect.Method;  
import java.net.URLEncoder;  
import java.util.Collection;  
import java.util.Iterator;  
import javax.servlet.http.HttpServletResponse;  
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;  
import org.apache.poi.ss.usermodel.Font;  

/**
 * 
* @Title: ExportExcelUtil.java  
* @Package com.jarmsystem.web.util  
* 类描述: 基于POI的javaee导出Excel工具类    
* @author lx  
* @date 2018年6月21日 下午6:10:25
* @version V1.0
 */
public class ExportExcelUtil {
/**  
  *  
  * @param response  
  *   请求  
  * @param fileName  
  *   文件名 如:"用户表"  
  * @param excelHeader  
  *   excel表头数组,存放"管理员#admin"格式字符串,"管理员"为excel标题行, "admin"为对象字段名  
  * @param dataList  
  *   数据集合,需与表头数组中的字段名一致,并且符合javabean规范  
  * @return 返回一个HSSFWorkbook  
  * @throws Exception  
  */  
public static <T> HSSFWorkbook export(HttpServletResponse response, String fileName, String[] excelHeader,  
   Collection<T> dataList) throws Exception {  
  // 设置请求   
  response.setContentType("application/x-download");//下面三行是关键代码,处理中文表名乱码问题 
          response.setCharacterEncoding("utf-8"); 
          response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1")+".xls");      
         // 创建一个Workbook,对应一个Excel文件  
  HSSFWorkbook wb = new HSSFWorkbook();  
  // 设置标题样式  
  HSSFCellStyle titleStyle = wb.createCellStyle();  
  // 设置单元格边框样式  
  titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框 细边线  
  titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下边框 细边线  
  titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框 细边线  
  titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框 细边线  
  // 设置单元格对齐方式  
  titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中  
  titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中  
  // 设置字体样式  
  Font titleFont = wb.createFont();  
  titleFont.setFontHeightInPoints((short)15);// 字体高度  
  titleFont.setFontName("黑体");// 字体样式  
  titleStyle.setFont(titleFont);  
  // 在Workbook中添加一个sheet,对应Excel文件中的sheet  
  HSSFSheet sheet = wb.createSheet(fileName);  
  // 标题数组  
  String[] titleArray = new String[excelHeader.length];  
  // 字段名数组  
  String[] fieldArray = new String[excelHeader.length];  
  for(int i = 0; i < excelHeader.length; i++) {  
   String[] tempArray = excelHeader[i].split("#");// 临时数组 分割#  
   titleArray[i] = tempArray[0];  
   fieldArray[i] = tempArray[1];  
  }  
  // 在sheet中添加标题行  
  HSSFRow row = sheet.createRow((int)0);// 行数从0开始  
  //需要序号才把下面注解打开
//   HSSFCell sequenceCell = row.createCell(0);// cell列 从0开始 第一列添加序号  
//   sequenceCell.setCellValue("序号");  
//   sequenceCell.setCellStyle(titleStyle);  
  sheet.autoSizeColumn(0);// 自动设置宽度  
          // 设置表格默认列宽度
          sheet.setDefaultColumnWidth(20);
  // 为标题行赋值  
  for(int i = 0; i < titleArray.length; i++) {  
   //需要序号就需要i+1     因为0号位被序号占用
   HSSFCell titleCell = row.createCell(i); 
   titleCell.setCellValue(titleArray[i]);  
   titleCell.setCellStyle(titleStyle);  
   sheet.autoSizeColumn(i + 1);// 0号位被序号占用,所以需+1  
  }  
  // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖  
  HSSFCellStyle dataStyle = wb.createCellStyle();  
  // 设置数据边框  
  dataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  dataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  dataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  dataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  // 设置居中样式  
  dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中  
  dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中  
  // 设置数据字体  
  Font dataFont = wb.createFont();  
  dataFont.setFontHeightInPoints((short)12);// 字体高度  
  dataFont.setFontName("宋体");// 字体  
  dataStyle.setFont(dataFont);  
  // 遍历集合数据,产生数据行  
  Iterator<T> it = dataList.iterator();  
  int index =0;  
  while(it.hasNext()) {  
   index++;// 0号位被占用 所以+1 
   row = sheet.createRow(index);   
   T t = (T) it.next();  
   // 利用反射,根据传过来的字段名数组,动态调用对应的getXxx()方法得到属性值  
   for(int i = 0; i < fieldArray.length; i++) {  
    //需要序号就需要i+1     
    HSSFCell dataCell = row.createCell(i);  
    dataCell.setCellStyle(dataStyle);  
    //需要序号就需要i+1
    sheet.autoSizeColumn(i);  
    String fieldName = fieldArray[i];  
    String getMethodName = "get"+ fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);// 取得对应getXxx()方法  
    Class<?extends Object> tCls = t.getClass();// 泛型为Object以及所有Object的子类  
    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});// 通过方法名得到对应的方法  
    Object value = getMethod.invoke(t, new Object[] {});// 动态调用方,得到属性值  
    if(value != null) {  
     dataCell.setCellValue(value.toString());// 为当前列赋值  
    }  
   }  
  }  
   
  OutputStream outputStream = response.getOutputStream();// 打开流  
  wb.write(outputStream);// HSSFWorkbook写入流  
  wb.close();// HSSFWorkbook关闭  
  outputStream.flush();// 刷新流  
  outputStream.close();// 关闭流  
  return wb;  
}  
// XSSFCellStyle.ALIGN_CENTER 居中对齐  
// XSSFCellStyle.ALIGN_LEFT 左对齐  
// XSSFCellStyle.ALIGN_RIGHT 右对齐  
// XSSFCellStyle.VERTICAL_TOP 上对齐  
// XSSFCellStyle.VERTICAL_CENTER 中对齐  
// XSSFCellStyle.VERTICAL_BOTTOM 下对齐  
   
// CellStyle.BORDER_DOUBLE 双边线  
// CellStyle.BORDER_THIN 细边线  
// CellStyle.BORDER_MEDIUM 中等边线  
// CellStyle.BORDER_DASHED 虚线边线  
// CellStyle.BORDER_HAIR 小圆点虚线边线  
// CellStyle.BORDER_THICK 粗边线  
}  

2.controller代码如下:

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.jarmsystem.web.base.BaseController;
import com.jarmsystem.web.base.pojo.ResultData;
import com.jarmsystem.web.base.pojo.web.sqlserver.T_Navigation;
import com.jarmsystem.web.dao.impl.oracle.UserDaoImpl;
import com.jarmsystem.web.model.Tb_User;
import com.jarmsystem.web.service.impl.SystemServiceImpl;
import com.jarmsystem.web.service.impl.TestServiceImpl;
import com.jarmsystem.web.util.CommonUtil;
import com.jarmsystem.web.util.CookieUtil;
import com.jarmsystem.web.util.ExportExcelUtil;
import com.jarmsystem.web.util.SecurityUtil;
import com.jarmsystem.web.util.SpringContextUtil;

/**
 * 
* @Title: ExportController.java  
* @Package com.jarmsystem.web.controller  
* 类描述:   导出
* @author lx  
* @date 2018年6月21日 下午5:21:15
* @version V1.0
 */
@Controller
public class ExportController  {

@RequestMapping("/excel")
public void excel(HttpServletRequest request,HttpServletResponse response,String export) {    
   export="管理员#admin,id#id,手机号码#adminphone";
   String[] excelHeader = export.split(",");  
   List<Tb_User> projectList = new ArrayList<Tb_User>();  
   Tb_User user=new Tb_User();
   Tb_User user2=new Tb_User();
   Tb_User user3=new Tb_User();
   user.setAdmin("行哥");
   user.setId("1111");
   user.setAdminphone("11111111");
   
   user2.setAdmin("行哥1号");
   user2.setId("2222");
   user2.setAdminphone("2222222");
   
   projectList.add(user);
   projectList.add(user2);
   projectList.add(user3);
  try{  
      ExportExcelUtil.export(response,"用户表", excelHeader, projectList);  
  }catch(Exception e) {  
   e.printStackTrace();  
  }
}

}

导出模板如下:

 

第二种导出.xlsx表格:

maevny依赖需要3.8版本的支持

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.8</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.8</version>
</dependency>


1.工具类:

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;


import javax.imageio.ImageIO;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * Excel 相关操作类(小数据量写入<=60000)
 */
public class ExcelUtils {


    private static final int DEFAULT_COLUMN_SIZE = 30;


    /**
     * 断言Excel文件写入之前的条件
     *
     * @param directory 目录
     * @param fileName  文件名
     * @return file
     * @throws IOException
     */
    private static File assertFile(String directory, String fileName) throws IOException {
        File tmpFile = new File(directory + File.separator + fileName + ".xlsx");
        if (tmpFile.exists()) {
            if (tmpFile.isDirectory()) {
                throw new IOException("File '" + tmpFile + "' exists but is a directory");
            }
            if (!tmpFile.canWrite()) {
                throw new IOException("File '" + tmpFile + "' cannot be written to");
            }
        } else {
            File parent = tmpFile.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent + "' could not be created");
                }
            }
        }
        return tmpFile;
    }


    /**
     * 日期转化为字符串,格式为yyyy-MM-dd HH:mm:ss
     */
    private static String getCnDate(Date date) {
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }


    /**
     * Excel 导出,POI实现
     *
     * @param fileName    文件名
     * @param sheetName   sheet页名称
     * @param columnNames 表头列表名
     * @param sheetTitle  sheet页Title
     * @param objects     目标数据集
     */
    public static File writeExcel(String directory, String fileName, String sheetName, List<String> columnNames,
                                  String sheetTitle, List<List<Object>> objects, boolean append) throws  IOException {
        File tmpFile = assertFile(directory, fileName);
        return exportExcel(tmpFile, sheetName, columnNames, sheetTitle, objects, append);
    }


    /**
     * Excel 导出,POI实现,先写入Excel标题,与writeExcelData配合使用
     * 先使用writeExcelTitle再使用writeExcelData
     *
     * @param directory   目录
     * @param fileName    文件名
     * @param sheetName   sheetName
     * @param columnNames 列名集合
     * @param sheetTitle  表格标题
     * @param append      是否在现有的文件追加
     * @return file
     * @throws ReportInternalException
     * @throws IOException
     */
    public static File writeExcelTitle(String directory, String fileName, String sheetName, List<String> columnNames,
                                       String sheetTitle, boolean append) throws  IOException {
        File tmpFile = assertFile(directory, fileName);
        return exportExcelTitle(tmpFile, sheetName, columnNames, sheetTitle, append);
    }


    /**
     * Excel 导出,POI实现,写入Excel数据行列,与writeExcelTitle配合使用
     * 先使用writeExcelTitle再使用writeExcelData
     *
     * @param directory 目录
     * @param fileName  文件名
     * @param sheetName sheetName
     * @param objects   数据信息
     * @return file
     * @throws ReportInternalException
     * @throws IOException
     */
    public static File writeExcelData(String directory, String fileName, String sheetName, List<List<Object>> objects)
            throws  IOException {
        File tmpFile = assertFile(directory, fileName);
        return exportExcelData(tmpFile, sheetName, objects);
    }


    /**
     * 导出字符串数据
     *
     * @param file        文件名
     * @param columnNames 表头
     * @param sheetTitle  sheet页Title
     * @param append      是否追加写文件
     * @return file
     * @throws ReportInternalException
     */
    private static File exportExcelTitle(File file, String sheetName, List<String> columnNames,
                                         String sheetTitle, boolean append) throws  IOException {
        // 声明一个工作薄
        Workbook workBook;
        if (file.exists() && append) {
            workBook = new XSSFWorkbook(new FileInputStream(file));
        } else {
            workBook = new XSSFWorkbook();
        }
        Map<String, CellStyle> cellStyleMap = styleMap(workBook);
        // 表头样式
        CellStyle headStyle = cellStyleMap.get("head");
        // 生成一个表格
        Sheet sheet = workBook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workBook.createSheet(sheetName);
        }
        //最新Excel列索引,从0开始
        int lastRowIndex = sheet.getLastRowNum();
        if (lastRowIndex > 0) {
            lastRowIndex++;
        }
        // 设置表格默认列宽度
        sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 0, columnNames.size() - 1));
        // 产生表格标题行
        Row rowMerged = sheet.createRow(lastRowIndex);
        lastRowIndex++;
        Cell mergedCell = rowMerged.createCell(0);
        mergedCell.setCellStyle(headStyle);
        mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
        // 产生表格表头列标题行
        Row row = sheet.createRow(lastRowIndex);
        for (int i = 0; i < columnNames.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(headStyle);
            RichTextString text = new XSSFRichTextString(columnNames.get(i));
            cell.setCellValue(text);
        }
        try {
            OutputStream ops = new FileOutputStream(file);
            workBook.write(ops);
            ops.flush();
            ops.close();
        } catch (IOException e) {
           System.err.println(e);
        }
        return file;
    }


    /**
     * 导出字符串数据
     *
     * @param file    文件名
     * @param objects 目标数据
     * @return
     * @throws ReportInternalException
     */
    private static File exportExcelData(File file, String sheetName, List<List<Object>> objects) throws  IOException {
        // 声明一个工作薄
        Workbook workBook;
        if (file.exists()) {
            workBook = new XSSFWorkbook(new FileInputStream(file));
        } else {
            workBook = new XSSFWorkbook();
        }


        Map<String, CellStyle> cellStyleMap = styleMap(workBook);
        // 正文样式
        CellStyle contentStyle = cellStyleMap.get("content");
        //正文整数样式
        CellStyle contentIntegerStyle = cellStyleMap.get("integer");
        //正文带小数整数样式
        CellStyle contentDoubleStyle = cellStyleMap.get("double");
        // 生成一个表格
        Sheet sheet = workBook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workBook.createSheet(sheetName);
        }
        //最新Excel列索引,从0开始
        int lastRowIndex = sheet.getLastRowNum();
        if (lastRowIndex > 0) {
            lastRowIndex++;
        }
        // 设置表格默认列宽度
        sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
        // 遍历集合数据,产生数据行,前两行为标题行与表头行
        for (List<Object> dataRow : objects) {
            Row row = sheet.createRow(lastRowIndex);
            lastRowIndex++;
            for (int j = 0; j < dataRow.size(); j++) {
                Cell contentCell = row.createCell(j);
                Object dataObject = dataRow.get(j);
                if (dataObject != null) {
                    if (dataObject instanceof Integer) {
                        contentCell.setCellStyle(contentIntegerStyle);
                        contentCell.setCellValue(Integer.parseInt(dataObject.toString()));
                    } else if (dataObject instanceof Double) {
                        contentCell.setCellStyle(contentDoubleStyle);
                        contentCell.setCellValue(Double.parseDouble(dataObject.toString()));
                    } else if (dataObject instanceof Long && dataObject.toString().length() == 13) {
                        contentCell.setCellStyle(contentStyle);
                        contentCell.setCellValue(getCnDate(new Date(Long.parseLong(dataObject.toString()))));
                    } else if (dataObject instanceof Date) {
                        contentCell.setCellStyle(contentStyle);
                        contentCell.setCellValue(getCnDate((Date) dataObject));
                    } else {
                        contentCell.setCellStyle(contentStyle);
                        contentCell.setCellValue(dataObject.toString());
                    }
                } else {
                    contentCell.setCellStyle(contentStyle);
                    // 设置单元格内容为字符型
                    contentCell.setCellValue("");
                }
            }
        }
        try {
            OutputStream ops = new FileOutputStream(file);
            workBook.write(ops);
            ops.flush();
            ops.close();
        } catch (IOException e) {
         System.err.println(e);
        }
        return file;
    }


    /**
     * 导出字符串数据
     *
     * @param file        文件名
     * @param columnNames 表头
     * @param sheetTitle  sheet页Title
     * @param objects     目标数据
     * @param append      是否追加写文件
     * @return
     * @throws ReportInternalException
     */
    private static File exportExcel(File file, String sheetName, List<String> columnNames,
                                    String sheetTitle, List<List<Object>> objects, boolean append) throws  IOException {
        // 声明一个工作薄
        Workbook workBook;
        if (file.exists() && append) {
            // 声明一个工作薄
            workBook = new XSSFWorkbook(new FileInputStream(file));
        } else {
            workBook = new XSSFWorkbook();
        }
        Map<String, CellStyle> cellStyleMap = styleMap(workBook);
        // 表头样式
        CellStyle headStyle = cellStyleMap.get("head");
        // 正文样式
        CellStyle contentStyle = cellStyleMap.get("content");
        //正文整数样式


        CellStyle contentIntegerStyle = cellStyleMap.get("integer");
        //正文带小数整数样式
        CellStyle contentDoubleStyle = cellStyleMap.get("double");
        // 生成一个表格
        Sheet sheet = workBook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workBook.createSheet(sheetName);
        }
        //最新Excel列索引,从0开始
        int lastRowIndex = sheet.getLastRowNum();
        if (lastRowIndex > 0) {
            lastRowIndex++;
        }
        // 设置表格默认列宽度
        sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 0, columnNames.size() - 1));
        // 产生表格标题行
        Row rowMerged = sheet.createRow(lastRowIndex);
        lastRowIndex++;
        Cell mergedCell = rowMerged.createCell(0);
        mergedCell.setCellStyle(headStyle);
        mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
        // 产生表格表头列标题行
        Row row = sheet.createRow(lastRowIndex);
        lastRowIndex++;
        for (int i = 0; i < columnNames.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(headStyle);
            RichTextString text = new XSSFRichTextString(columnNames.get(i));
            cell.setCellValue(text);
        }
        // 遍历集合数据,产生数据行,前两行为标题行与表头行
        for (List<Object> dataRow : objects) {
            row = sheet.createRow(lastRowIndex);
            lastRowIndex++;
            for (int j = 0; j < dataRow.size(); j++) {
                Cell contentCell = row.createCell(j);
                Object dataObject = dataRow.get(j);
                if (dataObject != null) {
                    if (dataObject instanceof Integer) {
                        contentCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        contentCell.setCellStyle(contentIntegerStyle);
                        contentCell.setCellValue(Integer.parseInt(dataObject.toString()));
                    } else if (dataObject instanceof Double) {
                        contentCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        contentCell.setCellStyle(contentDoubleStyle);
                        contentCell.setCellValue(Double.parseDouble(dataObject.toString()));
                    } else if (dataObject instanceof Long && dataObject.toString().length() == 13) {
                        contentCell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        contentCell.setCellStyle(contentStyle);
                        contentCell.setCellValue(getCnDate(new Date(Long.parseLong(dataObject.toString()))));
                    } else if (dataObject instanceof Date) {
                        contentCell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        contentCell.setCellStyle(contentStyle);
                        contentCell.setCellValue(getCnDate((Date) dataObject));
                    } else {
                        contentCell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        contentCell.setCellStyle(contentStyle);
                        contentCell.setCellValue(dataObject.toString());
                    }
                } else {
                    contentCell.setCellStyle(contentStyle);
                    // 设置单元格内容为字符型
                    contentCell.setCellValue("");
                }
            }
        }
        try {
            OutputStream ops = new FileOutputStream(file);
            workBook.write(ops);
            ops.flush();
            ops.close();
        } catch (IOException e) {
           System.err.println(e);
        }
        return file;
    }


    /**
     * 创建单元格表头样式
     *
     * @param workbook 工作薄
     */
    private static CellStyle createCellHeadStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 表头样式
        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        return style;
    }


    /**
     * 创建单元格正文样式
     *
     * @param workbook 工作薄
     */
    private static CellStyle createCellContentStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 正文样式
        style.setFillPattern(XSSFCellStyle.NO_FILL);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        return style;
    }


    /**
     * 单元格样式(Integer)列表
     */
    private static CellStyle createCellContent4IntegerStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 正文样式
        style.setFillPattern(XSSFCellStyle.NO_FILL);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));//数据格式只显示整数
        return style;
    }


    /**
     * 单元格样式(Double)列表
     */
    private static CellStyle createCellContent4DoubleStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 正文样式
        style.setFillPattern(XSSFCellStyle.NO_FILL);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));//保留两位小数点
        return style;
    }


    /**
     * 单元格样式列表
     */
    private static Map<String, CellStyle> styleMap(Workbook workbook) {
        Map<String, CellStyle> styleMap = new LinkedHashMap<>();
        styleMap.put("head", createCellHeadStyle(workbook));
        styleMap.put("content", createCellContentStyle(workbook));
        styleMap.put("integer", createCellContent4IntegerStyle(workbook));
        styleMap.put("double", createCellContent4DoubleStyle(workbook));
        return styleMap;
    }
}

2.测试类:

import java.io.IOException;
import java.sql.Date;
import java.util.LinkedList;
import java.util.List;

public class Excel2007Test {
    public static void main(String[] args) throws IOException {
        String sheetName = "行哥测试";
        String sheetTitle = "行哥测试";
        List<String> columnNames = new LinkedList<>();
        columnNames.add("日期-String");
        columnNames.add("日期-Date");
        columnNames.add("时间戳-Long");
        columnNames.add("客户编码");
        columnNames.add("整数");
        columnNames.add("带小数的正数");


        //写入标题--第二种方式
        Excel2007Utils.writeExcelTitle("D:\\tset", "biaoming", sheetName, columnNames, sheetTitle, false);


        List<List<Object>> objects = new LinkedList<>();
        for (int i = 0; i < 2000; i++) {
            List<Object> dataA = new LinkedList<>();
            dataA.add("http://img05.com/images/20/tooopen_sy_139205349641.jpg");
            dataA.add(new Date(1451036631012L));
            dataA.add(1451036631012L);
            dataA.add("http://img05com/images/20150820/tooopen_sy_139205349641.jpg");
            dataA.add(i);
            dataA.add(1.323 + i);
            objects.add(dataA);
        }
        try {
            //写入数据--第二种方式
           Excel2007Utils.writeExcelData("D:\\tset", "biaoming", sheetName, objects);
            //直接写入数据--第一种方式
           Excel2007Utils.writeExcel("D:\\tset", "biaoming", sheetName, columnNames, sheetTitle, objects, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如果你是湖南的 欢迎加入 湖南人在深圳-Java群:557651502

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值