Java Excel文件导入导出

1.maven依赖

首先引入POI包依赖

<dependency>

  <groupId>org.apache.poi</groupId>

  <artifactId>poi</artifactId>

  <version>4.1.2</version>

</dependency>

<dependency>

  <groupId>org.apache.poi</groupId>

  <artifactId>poi-ooxml</artifactId>

  <version>4.1.2</version>

</dependency>



2.API   

大家需要了解一下相关的API类,便于后面理解代码逻辑和排查问题,重写相关逻辑实现自己的业务需求。

  1.import org.apache.poi.ss.usermodel.Workbook,对应Excel文档;

  2.import org.apache.poi.hssf.usermodel.HSSFWorkbook,对应xls格式的Excel文档;

  3.import org.apache.poi.xssf.usermodel.XSSFWorkbook,对应xlsx格式的Excel文档;

  4.import org.apache.poi.ss.usermodel.Sheet,对应Excel文档中的一个sheet;

  5.import org.apache.poi.ss.usermodel.Row,对应一个sheet中的一行;

  6.import org.apache.poi.ss.usermodel.Cell,对应一个单元格。




3.导入

public class ImportExcelUtil {

    private static final String EXCEL_XLS_SUFFIX = ".xls";

    private static final String EXCEL_XLSX_SUFFIX = ".xlsx";

    /**

    * 读取Excel数据内容

    *

    * @param rowIndex    指定行号

    * @param columnIndex 指定列号

    * @return Map 包含单元格数据内容的Map对象

    */

    public static List<Map<Integer, Object>> readExcelContent(String filepath, Integer rowIndex, Integer columnIndex) throws Exception {

        List<Map<Integer, Object>> returnList = new LinkedList<>();

        Workbook wb = null;

        Sheet sheet;

        Row row;

        try {

            InputStream is = new FileInputStream(filepath);

            if (filepath.endsWith(EXCEL_XLS_SUFFIX)) {

                wb = new HSSFWorkbook(is);

            } else if (filepath.endsWith(EXCEL_XLSX_SUFFIX)) {

                wb = new XSSFWorkbook(is);

            }

            if (wb == null) {

                throw new Exception("Workbook对象为空!");

            }

            sheet = wb.getSheetAt(0);

            //解析文件总行数、总列数

            int rowNum = rowIndex != null ? rowIndex : sheet.getLastRowNum();

            row = sheet.getRow(0);

            int colNum = columnIndex != null ? columnIndex : row.getLastCellNum();

            //循环列

            for (int colIndex = colNum; colIndex > 0; colIndex--) {

                Cell cell = row.getCell(colIndex);

                if (cell != null && !"".equals(cell.toString())) {

                    colNum = colIndex;

                    break;

                }

            }

            logger.info("have data col:{}", colNum);

            // 正文内容应该从第二行开始,第一行为表头的标题

            for (int i = 0; i <= rowNum; i++) {

                row = sheet.getRow(i);

                int j = 0;

                int size = (int) (colNum / .75f) + 1;

                //存储单元格数据

                Map<Integer, Object> cellValue = new LinkedHashMap<>(size);

                if (row == null) {

                    continue;

                }

                while (j <= colNum) {

                    Cell cell = row.getCell(j);

                    String value = "";

                    //日期单元格需格式化日期

                    if (cell != null) {

                        if (cell.getCellType() == CellType.NUMERIC) {

                            if (HSSFDateUtil.isCellDateFormatted(cell)) {

                                Date d = cell.getDateCellValue();

                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

                                value = formatter.format(d);

                            } else if (cell.toString().contains("E")) {

                                DecimalFormat nf = new DecimalFormat("0");

                                value = nf.format(cell.getNumericCellValue());

                            } else {

                                value = cell.toString().endsWith(".0") ? cell.toString().replace(".0", "") : cell.toString().trim();

                            }

                        } else if (cell.getCellType() == CellType.FORMULA) {

                            value = String.valueOf(cell.getNumericCellValue());

                        } else {

                            value = cell.toString().trim();

                        }

                    }

                    cellValue.put(j, value);

                    j++;

                }

              returnList.add(cellValueMap);

            }

            wb.close();

        } catch (FileNotFoundException e) {

            logger.error("FileNotFoundException", e);

        } catch (IOException e) {

            logger.error("IOException", e);

        } finally {

            if (wb != null) {

                wb.close();

            }

        }

        return returnList;

    }

}


4.导出

public class ExportExcelUtil {

/**

* 导出excel文件,表头为一维数组表示不用合并单元格

* @param sheetName

* @param excelTitle

* @param dataCollection

* @param <T>

* @return

*/

public static<T> HSSFWorkbook exportExcel(String sheetName, String[] excelTitle, Collection<T> dataCollection) {

//创建一个Excel文件

HSSFWorkbook workbook = new HSSFWorkbook();

//创建一个Sheet表格工作空间

HSSFSheet sheet = workbook.createSheet(sheetName);

HSSFCellStyle style = workbook.createCellStyle();

//设置表格默认宽度

sheet.setDefaultColumnWidth(20);

//设置表格的表头

HSSFCell cellHeader;

HSSFRow row = sheet.createRow(0);

for (int i = 0; i < excelTitle.length; i++) {

//创建单元格表头

cellHeader = row.createCell(i);

cellHeader.setCellValue(new HSSFRichTextString(excelTitle[i]));

}

//匹配表头设置单元格的值

setWorkBookValue(sheet, dataCollection,0, style);

return workbook;

}

/**

    * (根据自定义)把具体数据写入到excel中

    * @param sheet

    * @param dataCollection

    * @param index

    * @param style

    * @param <T>

    */

    @SuppressWarnings("unchecked")

private static<T> void setWorkBookValue(HSSFSheet sheet,Collection<T> dataCollection, int index,HSSFCellStyle style){

T t;

Object[] fields;

String fieldName;

String getMethodName;

HSSFCell cell;

HSSFRow row;

Class tClass;

Method getMethod;

Object value;

//遍历集合设置单元格值

Iterator<T> it = dataCollection.iterator();

while(it.hasNext()){

//创建一行单元格

index ++;

row = sheet.createRow(index);

//获取数据

t = it.next();

//利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值

fields = t.getClass().getDeclaredFields();

for(int i = 0; i < fields.length; i++){

cell = row.createCell(i);

style.setAlignment(HorizontalAlignment.LEFT);

cell.setCellStyle(style);

//利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值

Field[] newFields = t.getClass().getDeclaredFields();

fieldName = newFields[i].getName();

getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

try {

tClass = t.getClass();

getMethod = tClass.getMethod(getMethodName, new Class[]{});

value = getMethod.invoke(t, new Object[]{});

setCellValue(value,cell);

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

/**

* value格式校验

*/

private static void setCellValue(Object value,HSSFCell cell){

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String textValue = null;

Pattern pattern = Pattern.compile(RULE);

Matcher matcher;

HSSFRichTextString richTextString;

if (!StringUtils.isEmpty(value)){

//value进行类型转换

if (value instanceof Integer) {

cell.setCellValue((Integer) value);

} else if (value instanceof Float) {

textValue = String.valueOf(value);

cell.setCellValue(textValue);

} else if (value instanceof Double) {

textValue = String.valueOf(value);

cell.setCellValue(textValue);

} else if (value instanceof Long) {

cell.setCellValue((Long) value);

} else if (value instanceof Boolean) {

textValue = "是";

if (!(Boolean) value) {

textValue = "否";

}

} else if (value instanceof Date) {

textValue = sdf.format((Date) value);

} else {

// 其它数据类型都当作字符串简单处理

textValue = value.toString();

}

if (textValue != null) {

matcher = pattern.matcher(textValue);

if (matcher.matches()) {

// 是数字当作double处理

cell.setCellValue(Double.parseDouble(textValue));

} else {

richTextString = new HSSFRichTextString(textValue);

cell.setCellValue(richTextString);

}

}

}

}

/**

* excel 导出文件

* @param response

* @param workbook

* @param fileName

* @throws IOException

*/

public static void exportExcelFile(HttpServletResponse response, HSSFWorkbook workbook, String fileName) throws IOException {

if (workbook != null) {

response.reset();

//指定下载的文件名

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

String filePrefix = sdf.format(new Date());

response.setContentType("application/vnd.ms-excel");

            response.setCharacterEncoding("utf-8");

fileName = URLEncoder.encode(filePrefix + "_" + fileName, "UTF-8").replaceAll("\\+", "%20");

            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

BufferedOutputStream bufferedOutput = null;

try {

bufferedOutput = new BufferedOutputStream(response.getOutputStream());

workbook.write(bufferedOutput);

bufferedOutput.flush();

} catch (IOException e) {

    e.printStackTrace();

throw e;

} finally {

if (bufferedOutput != null) {

try {

bufferedOutput.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

}


4 调用导出

public void exportFile(String objectJson, HttpServletResponse response) throws Exception {

//省略业务代码

        HSSFWorkbook workbook = ExportExcelUtil.exportExcel(SHEET_NAME, TITLE_LINE, xxxList);

        ExportExcelUtil.exportExcelFile(response, workbook, FILE_NAME);

    }

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335