`
happyqing
  • 浏览: 3212900 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

poi导出excel,不使用模板的

    博客分类:
  • poi
阅读更多

 

poi导出excel,基于模板的比较简单,这个列是动态的,所已选择不基于模板的,相对复杂些,要设置样式。包括:设置列宽、设置字体、设置边框

 

package com.urthink.jxsh.util;

import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**
 * 导出excel
 * @author happyqing
 * @date 2017-09-18
 */
public class ExcelExport {
    
	/**
	 * 导出excel
	 * @param list				数据列表 List<E> 实体类列表
	 * @param headers			列标题,以英文逗号分割,必传
	 * @param includes		属性,以英文逗号分割,必传
	 * @param filePath			导出文件全路径
	 * @param sheetName			sheet名称:sheet1
	 * @param dataPattern		日期格式:yyyy-MM-dd HH:mm:ss
	 * @throws Exception		另一个程序正在使用此文件,进程无法访问
	 */
    public static <E> void exportListEntity(List<E> list, String headers, String includes, String filePath, String sheetName, String dataPattern) throws Exception{
        //工作簿
        Workbook wb;
        
        // 创建模板工作表
        if (filePath.endsWith(".xls")) {
        	wb = new HSSFWorkbook();
        } else {
        	//templatewb = new XSSFWorkbook(new FileInputStream(filePath));
        	//wb = new XSSFWorkbook();
        	wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘,解决内存溢出
        }
        
        String[] headerArr = headers.split(",");
        String[] includeArr = includes.split(",");
        List<String> includeList = Arrays.asList(includeArr);;
        
        //字体
        Font font = wb.createFont();   
        //font.setFontHeightInPoints((short)14);   
        //font.setColor(IndexedColors.DARK_BLUE.getIndex());   
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        
        //样式
        CellStyle styleBOLD = createBorderedStyle(wb);
        styleBOLD.setFont(font);
        styleBOLD.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        styleBOLD.setWrapText(false); //自动换行
        
        //样式
        CellStyle styleWrap = createBorderedStyle(wb);
        styleWrap.setWrapText(false);
        styleWrap.setVerticalAlignment(CellStyle.VERTICAL_TOP);
        
        //表
        Sheet sheet = wb.createSheet(sheetName);
        //列宽
        //sheet.autoSizeColumn(( short ) 0 ); // 调整第一列宽度
        //sheet.SetColumnWidth(1, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256,中文的要再乘以2
//        sheet.setColumnWidth(0, 3000);
       
        //行
        Row row = sheet.createRow(0);
        //单元格
        Cell cell;
        //写入标题行
        for(int i=0; i<headerArr.length; i++){
            cell = row.createCell(i);
            cell.setCellValue(headerArr[i]);
            cell.setCellStyle(styleBOLD);
        }
        
        //写入数据
        E e;			//实体类
        Field[] fields;	//属性数组
        Field field;	//属性
        Object value;	//属性值
        DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ss
        for(int i=0; i<list.size(); i++){
        	row = sheet.createRow(i+1);
        	e = list.get(i);
        	// 利用反射,获取属性数组
            fields = e.getClass().getDeclaredFields();
            for(int f=0,c=0; f<fields.length; f++){
            	 field = fields[f];
            	 if(includeList.contains(field.getName())){
	            	 cell = row.createCell(c);
	            	 cell.setCellStyle(styleWrap);
	            	//cell.setCellType(Cell.CELL_TYPE_STRING);
	            	 //field.getName();
	            	 //field.getType();
	            	 field.setAccessible(true);	//设置些属性是可以访问的
	                 value = field.get(e);		//得到此属性的值
	                 //Byte,Short,Int,Long,Float,Double,Boolean,Char, String,Date,BigDecimal,byte[]
	                 //cell.setCellValue: boolean,Calendar,Date,double,RichTextString,String
	                 if(value==null){
	                	 
	                 } else if (value instanceof Date){  
	                	 cell.setCellValue(dtf.format((Date)value));
	                 } else {
	                	 cell.setCellValue(value.toString());
	                 }
	                 c++;
            	 }
            }
        }

        //写入文件
        FileOutputStream fOut = new FileOutputStream(filePath);
        wb.write(fOut);
    }
    
    /**
	 * 导出excel
	 * @param list				数据列表 List<Map<String, Object>>
	 * @param headers			列标题,以英文逗号分割,必传
	 * @param includes			字段名,以英文逗号分割,必传
	 * @param filePath			导出文件全路径
	 * @param sheetName			sheet名称:sheet1
	 * @param dataPattern		日期格式:yyyy-MM-dd HH:mm:ss
	 * @throws Exception		另一个程序正在使用此文件,进程无法访问
	 */
    public static void exportListMap(List<Map<String, Object>> list, String headers, String includes, String filePath, String sheetName, String dataPattern) throws Exception{
        //工作簿
        Workbook wb;
        
        // 创建模板工作表
        if (filePath.endsWith(".xls")) {
        	wb = new HSSFWorkbook();
        } else {
        	//templatewb = new XSSFWorkbook(new FileInputStream(filePath));
        	//wb = new XSSFWorkbook();
        	wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘,解决内存溢出
        }
        
        String[] headerArr = headers.split(",");
        String[] includeArr = includes.split(",");
        
        //字体
        Font font = wb.createFont();   
        //font.setFontHeightInPoints((short)14);   
        //font.setColor(IndexedColors.DARK_BLUE.getIndex());   
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        
        //样式
        CellStyle styleBOLD = createBorderedStyle(wb);
        styleBOLD.setFont(font);
        styleBOLD.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        styleBOLD.setWrapText(false); //自动换行
        
        //样式
        CellStyle styleWrap = createBorderedStyle(wb);
        styleWrap.setWrapText(false);
        styleWrap.setVerticalAlignment(CellStyle.VERTICAL_TOP);
        
        //表
        Sheet sheet = wb.createSheet(sheetName);
        //列宽
        //sheet.autoSizeColumn(( short ) 0 ); // 调整第一列宽度
        //sheet.SetColumnWidth(1, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256,中文的要再乘以2
//        sheet.setColumnWidth(0, 3000);
       
        //行
        Row row = sheet.createRow(0);
        //单元格
        Cell cell;
        //写入标题行
        for(int i=0; i<headerArr.length; i++){
            cell = row.createCell(i);
            cell.setCellValue(headerArr[i]);
            cell.setCellStyle(styleBOLD);
        }
        
        Map rowMap;			//行map
        String fieldName;	//字段名
        Object value;		//属性值
        DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ss
        for(int i=0; i<list.size(); i++){
        	row = sheet.createRow(i+1);
        	rowMap = list.get(i);
            for(int f=0,c=0; f<includeArr.length; f++){
            	fieldName = includeArr[f];
            	 cell = row.createCell(c);
            	 cell.setCellStyle(styleWrap);
                 value = rowMap.get(fieldName);		//得到此字段的值
                 if(value==null){
                	 
                 } else if (value instanceof Date){  
                	 cell.setCellValue(dtf.format((Date)value));
                 } else {
                	 cell.setCellValue(value.toString());
                 }
                 c++;
            }
        }

        //写入文件
        FileOutputStream fOut = new FileOutputStream(filePath);
        wb.write(fOut);
    }
    
    /**
	 * 导出excel
	 * @param list				数据列表 List<List<Object>>,List<Object>是一行数据
	 * @param headers			列标题,以英文逗号分割,必传
	 * @param filePath			导出文件全路径
	 * @param sheetName			sheet名称:sheet1
	 * @param dataPattern		日期格式:yyyy-MM-dd HH:mm:ss
	 * @throws Exception		另一个程序正在使用此文件,进程无法访问
	 */
    public static void exportListList(List<List<Object>> list, String headers, String filePath, String sheetName, String dataPattern) throws Exception{
        //工作簿
        Workbook wb;
        
        // 创建模板工作表
        if (filePath.endsWith(".xls")) {
        	wb = new HSSFWorkbook();
        } else {
        	//templatewb = new XSSFWorkbook(new FileInputStream(filePath));
        	//wb = new XSSFWorkbook();
        	wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘,解决内存溢出
        }
        
        String[] headerArr = headers.split(",");
        
        //字体
        Font font = wb.createFont();   
        //font.setFontHeightInPoints((short)14);   
        //font.setColor(IndexedColors.DARK_BLUE.getIndex());   
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        
        //样式
        CellStyle styleBOLD = createBorderedStyle(wb);
        styleBOLD.setFont(font);
        styleBOLD.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        styleBOLD.setWrapText(false); //自动换行
        
        //样式
        CellStyle styleWrap = createBorderedStyle(wb);
        styleWrap.setWrapText(false);
        styleWrap.setVerticalAlignment(CellStyle.VERTICAL_TOP);
        
        //表
        Sheet sheet = wb.createSheet(sheetName);
        //列宽
        //sheet.autoSizeColumn(( short ) 0 ); // 调整第一列宽度
        //sheet.SetColumnWidth(1, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256,中文的要再乘以2
//        sheet.setColumnWidth(0, 3000);
       
        //行
        Row row = sheet.createRow(0);
        //单元格
        Cell cell;
        //写入标题行
        for(int i=0; i<headerArr.length; i++){
            cell = row.createCell(i);
            cell.setCellValue(headerArr[i]);
            cell.setCellStyle(styleBOLD);
        }
        
        List<Object> dataRow;
        Object value;	//属性值
        DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ss
        for(int i=0; i<list.size(); i++){
            dataRow = list.get(i);
            row = sheet.createRow(i+1);
            for(int j=0; j<dataRow.size(); j++){
                cell = row.createCell(j);
                cell.setCellStyle(styleWrap);
            	//cell.setCellType(Cell.CELL_TYPE_STRING);
                value = dataRow.get(j);
                if(value==null){
               	 
                } else if (value instanceof Date){  
               	 cell.setCellValue(dtf.format((Date)value));
                } else {
               	 cell.setCellValue(value.toString());
                }
            }
        }
        
        //写入文件
        FileOutputStream fOut = new FileOutputStream(filePath);
        wb.write(fOut);
    }
    
    private static CellStyle createBorderedStyle(Workbook wb){   
        CellStyle style = wb.createCellStyle();   
        style.setBorderRight(CellStyle.BORDER_THIN);   
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());   
        style.setBorderBottom(CellStyle.BORDER_THIN);   
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());   
        style.setBorderLeft(CellStyle.BORDER_THIN);   
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());   
        style.setBorderTop(CellStyle.BORDER_THIN);   
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());   
        return style;   
    }
}

 

得到单元格的字符串内容,注意:有的excel里有隐藏列

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

 

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.DateUtil;

// 得到单元格的字符串内容
	public static String getCellValue(Cell cell) {
		DecimalFormat df = new DecimalFormat("#");
		if (cell == null)
			return "";
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				return sdf.format(cell.getDateCellValue()).toString();
				// return sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())).toString();
			}
			return df.format(cell.getNumericCellValue());
		case Cell.CELL_TYPE_STRING:
			// System.out.println(cell.getStringCellValue());
			return cell.getStringCellValue();
		case Cell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();
		case Cell.CELL_TYPE_BLANK:
			return "";
		case Cell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue() + "";
		case Cell.CELL_TYPE_ERROR:
			return cell.getErrorCellValue() + "";
		}
		return "";
	}
 

 

下载片段:

//下载
        try {
        	fileName= new String(fileName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        response.setContentType("application/octet-stream"); //MIME类型
        //该步是最关键的一步,使用setHeader()方法弹出"是否要保存"的对话框,打引号的部分都是固定的值,不要改变   
        response.setHeader("Content-disposition","attachment;filename="+fileName);
        //写入文件
        wb.write(response.getOutputStream());

 

参考:

http://www.iteye.com/problems/65838

 

分享到:
评论

相关推荐

    springboot+poi导出指定格式Excel模板

    springboot+poi导出指定格式Excel模板,完整项目,导出即用。springboot+poi导出指定格式Excel模板,完整项目,导出即用。springboot+poi导出指定格式Excel模板,完整项目,导出即用。springboot+poi导出指定格式...

    POI使用Excel模板文件循环输出行并导出Excel

    在这个特定的例子中,我们将讨论如何使用POI库基于一个Excel模板文件循环输出数据行,并将结果导出为新的Excel文件。 首先,我们需要理解POI库的基本概念。POI提供了HSSF(Horizontally SpreadSheet Format)和XSSF...

    poi导出根据模板导出excel和简单列表导出excel源码

    在本案例中,我们关注的是如何使用 Apache POI 库来导出 Excel 文件,特别是根据模板导出和简单列表导出。下面将详细介绍这个过程。 1. **Apache POI 概述** Apache POI 提供了 Java API 来读写 Microsoft Office ...

    poi excel 模板读取并导出带公式的excel文档

    ### POI Excel 模板读取并导出带公式的Excel文档 #### 一、概述 ...综上所述,通过使用Apache POI库结合Excel模板文件,可以高效地实现批量数据的导入导出,并保持原有的公式计算能力,大大提高了工作效率。

    poi导出excel生成下拉列表

    poi作为导出excel常用的工具,方便快捷。对于excel指定下拉列表的列,如何生成呢?本文提供如何生成下拉列表的excel列

    POI实现的基于动态模板的EXCEL数据导出

    标题中的“POI实现的基于动态模板的EXCEL数据导出”是指利用Apache POI库来创建一个可以动态填充数据的Excel模板,从而实现大量数据的高效导出。Apache POI是一个开源项目,它允许Java开发者读写Microsoft Office...

    poi基于模板导出excel

    ### POI 基于模板导出 Excel 的实现方法 #### 概述 Apache POI 是一个用于读写 Microsoft Office 格式文件的 Java 库,其中包括对 Excel 文件的支持。在实际开发过程中,经常会遇到需要根据现有的 Excel 模板来...

    springboot + poi导出指定格式Excel模板

    在本文中,我们将深入探讨如何使用SpringBoot和Apache POI库来导出指定格式的Excel模板。Apache POI是Java领域广泛使用的库,用于读写Microsoft Office格式的文件,其中包括Excel(.xlsx 和 .xls)文件。SpringBoot...

    jxls-poi导出excel示例代码文件

    4. **导出Excel**:最后,`jxls-poi`会生成一个新的Excel文件,其中包含了从JSON数据填充后的内容。你可以选择保存到本地或者直接通过HTTP响应发送给用户下载。 具体代码示例可能如下: ```java import org.jxls....

    poi 基于excel模板导出功能

    本篇将深入探讨如何利用Apache POI实现基于Excel模板的导出功能。 一、Apache POI基本概念 1. HSSF与XSSF:Apache POI提供了两种处理Excel的API,HSSF用于处理.xls(Excel 97-2003)格式,而XSSF则用于处理.xlsx...

    java基于poi通过excel模板导出

    本篇文章将详细探讨如何利用POI库基于模板来导出Excel文档。 首先,我们需要理解Apache POI的工作原理。POI提供了HSSF(Horrible Spreadsheet Format)和XSSF(XML Spreadsheet Format)两个组件,分别用于处理老...

    POI 生成EXCEL2007【含例子】

    标题 "POI 生成EXCEL2007【含例子】" 涉及到的知识点主要集中在Apache POI库的使用上,这是一个强大的Java API,用于读取、写入和修改Microsoft Office格式的文件,特别是Excel文件。在这个场景中,重点是创建和操作...

    POI按照模板导出Excel

    本教程将深入讲解如何使用Apache POI按照模板导出Excel文件。 一、Apache POI简介 Apache POI是一个强大的库,它允许Java程序员操作Microsoft Office格式的文件。在Excel方面,POI支持HSSF(Horizontally Stored ...

    通过jxls和poi导出excel的dome

    在"通过jxls和poi导出excel的dome"中,我们将看到以下核心步骤: 1. **创建Excel模板**:首先,你需要设计一个Excel模板,包含所有所需的样式和布局。模板中的某些区域将被标记为数据注入点,这些通常用特定的jxls...

    java使用 POI Excel模板导出数据

    这篇博客"java使用POI Excel模板导出数据"探讨了如何利用POI库在Java中创建Excel模板并填充数据。下面将详细介绍这个过程以及相关知识点。 首先,我们需要理解Apache POI的基本概念。POI是Apache软件基金会的一个...

    java基于poi使用excel模板导出

    本篇文章将深入探讨如何使用Apache POI基于模板来导出Excel文件,以满足数据展示和报告生成的需求。 首先,我们需要理解Apache POI的工作原理。POI库允许Java程序与Microsoft Excel的文件格式进行交互,提供了对XLS...

    java poi导出excel含工具类以及示例

    String outputFile = "D:\\excel\\excel.xlsx"; OutputStream outputStream = new FileOutputStream(outputFile); UtilExcel utilExcel = new UtilExcel(); String titles = "所属区域,所属车间,当前处理人,描述...

    poi实现导入数据到excel模板

    poi实现导入数据到excel模板,本来想上传poi的jar包,谁知限制我只能上传15M的文件,汗。。。。。 不知道啥时候开始要分了... 代码见: https://github.com/thisisnohi/nohi-doc poi实现导入数据到excel模板。...

    JAVA poi 做EXCEL导出(包含图片) 完整版

    本教程将详细介绍如何使用JAVA POI库来创建一个包含图片的完整Excel导出功能。 首先,你需要在项目中引入Apache POI依赖。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖: ```xml &lt;groupId&gt;org.apache....

    poi包 EXCEL模板读取填数据并导出以及在模板某行插入新的行

    标题中的“poi包 EXCEL模板读取填数据并导出以及在模板某行插入新的行”涉及到了Apache POI库的使用,这是一个Java API,专门用于处理Microsoft Office格式的文件,如Excel。以下是对这个主题的详细解释: Apache ...

Global site tag (gtag.js) - Google Analytics