导入导出专栏(poi,jxls)

poi自定义样式导出

使用Java main方法实现导出

复制到java程序运行可以直接导出, (导出内容来自百度),前提是引入poi jar包,我没找到连接,有资源的希望提供一下

  public static void main(String[] args) throws IOException {

        //创建HSSFWorkbook对象
        HSSFWorkbook wb = new HSSFWorkbook();

        // 设置字体样式
        HSSFFont font = wb.createFont();
        // 字体大小
        font.setFontHeightInPoints((short) 30);
        // 字体
        font.setFontName("楷体");
        // 颜色
        font.setColor(HSSFColor.GREEN.index);

        // 设置单元格样式 红色
        HSSFCellStyle rad = wb.createCellStyle();
        rad.setFillForegroundColor(IndexedColors.RED.getIndex());
        rad.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置单元格样式 绿色
        HSSFCellStyle green = wb.createCellStyle();
        green.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        green.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 字体样式
        HSSFCellStyle fond = wb.createCellStyle();
        fond.setFont(font);

        //建立sheet对象 ,取名'成绩表'
        HSSFSheet sheet=wb.createSheet("成绩表");

        //在sheet里创建第一行,参数为行索引
        HSSFRow row1=sheet.createRow(0);
        //创建单元格
        HSSFCell cell=row1.createCell(0);

        //设置单元格内容
        cell.setCellValue("学生成绩表");
        //设置单元格颜色,想要什么颜色就传什么参数, rad || green
        cell.setCellStyle(fond);

        //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列, 第一列为0,第二列为1
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));

        //在sheet里创建第二行
        // 这里要根据实际需求使用for动态生成行(row),我这里做demo就写死了
        HSSFRow row2=sheet.createRow(1);

        //创建单元格并设置单元格内容  row2.createCell(0)创建第二行第一个单元格
        // 这里要根据实际需求使用for动态生成列,也可以自己手写
        HSSFCell cell1 = row2.createCell(0);
        cell1.setCellValue("姓名");
        //一样的设置颜色()
        cell1.setCellStyle(rad);
        // 注意: 上面的写法正确;
        // 错误写法:row2.createCell(0).setCellValue("姓名");
        // ----- :row2.createCell(0).setCellStyle(rad);
        // 影响: 这样等于构建两个单元格,第二个会吧第一个覆盖,所以只会显示颜色,汉字被覆盖

        row2.createCell(1).setCellValue("班级");

        row2.createCell(2).setCellValue("语文成绩");

        row2.createCell(3).setCellValue("数学成绩");

        row2.createCell(4).setCellValue("英语成绩");

        //在sheet里创建第三行

        HSSFRow row3=sheet.createRow(2);

        row3.createCell(0).setCellValue("小明");

        row3.createCell(1).setCellValue("1班");

        row3.createCell(2).setCellValue(80);

        row3.createCell(3).setCellValue(75);

        row3.createCell(4).setCellValue(88);

        HSSFRow row4=sheet.createRow(3);

        row4.createCell(0).setCellValue("小红");

        row4.createCell(1).setCellValue("1班");

        row4.createCell(2).setCellValue(82);

        row4.createCell(3).setCellValue(70);

        row4.createCell(4).setCellValue(90);

        //输出Excel文件, 我本机维护好的demo文件夹,没有这个文件加会报错, System.currentTimeMillis() 一串顺随机数
        String fileName = "D:\\demo\\" + System.currentTimeMillis() + ".xlsx";
        File aa = new File(fileName);
        // 写出文件流
        wb.write(aa);
        // 关闭文件流
        wb.close();
    }

基于springboot导出

Controller类内容:单纯的调用方法

package com.boot.controller;

import com.boot.entity.ExcelImport;
import com.boot.service.ExcelService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Excel Controller
 */
@RestController
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @GetMapping("poiExport")
    public void poiImport(HttpServletResponse response) throws IOException {
        excelService.poiExport(response);
    }
}

service内容:详细解释在代码注释,HttpServletrequest 与HttpServletResponse区别和response内容类型解释在代码后面

@Override
    public void poiExport(HttpServletResponse response) throws IOException {
        //创建文件名(改)
        String fileName = "成绩表.xls";
        // 解决中文乱码问题
        String fileNameURL = URLEncoder.encode(fileName, "UTF-8");
        // vnd.ms-excel 具体意义见下response内容类型解释
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameURL);

        //创建HSSFWorkbook对象
        HSSFWorkbook wb = new HSSFWorkbook();
        // 设置字体样式
        HSSFFont font = wb.createFont();
        // 字体大小
        font.setFontHeightInPoints((short) 30);
        // 字体
        font.setFontName("楷体");
        // 颜色
        font.setColor(HSSFColor.GREEN.index);

        // 设置单元格样式 红色
        HSSFCellStyle rad = wb.createCellStyle();
        rad.setFillForegroundColor(IndexedColors.RED.getIndex());
        rad.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置单元格样式 绿色
        HSSFCellStyle green = wb.createCellStyle();
        green.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        green.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 字体样式
        HSSFCellStyle fond = wb.createCellStyle();
        fond.setFont(font);

        //建立sheet对象 ,取名'成绩表'
        HSSFSheet sheet = wb.createSheet("成绩表");

        //在sheet里创建第一行,参数为行索引
        HSSFRow row1 = sheet.createRow(0);
        //创建单元格
        HSSFCell cell = row1.createCell(0);

        //设置单元格内容
        cell.setCellValue("学生成绩表");
        //设置单元格颜色,想要什么颜色就传什么参数, rad || green
        cell.setCellStyle(fond);

        //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列, 第一列为0,第二列为1
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

        //在sheet里创建第二行
        // 这里要根据实际需求使用for动态生成行(row),我这里做demo就写死了
        HSSFRow row2 = sheet.createRow(1);

        //创建单元格并设置单元格内容  row2.createCell(0)创建第二行第一个单元格
        // 这里要根据实际需求使用for动态生成列,也可以自己手写
        HSSFCell cell1 = row2.createCell(0);
        cell1.setCellValue("姓名");
        //一样的设置颜色()
        cell1.setCellStyle(rad);
        // 注意: 上面的写法正确;
        // 错误写法:row2.createCell(0).setCellValue("姓名");
        // ----- :row2.createCell(0).setCellStyle(rad);
        // 影响: 这样等于构建两个单元格,第二个会吧第一个覆盖,所以只会显示颜色,汉字被覆盖

        row2.createCell(1).setCellValue("班级");

        row2.createCell(2).setCellValue("语文成绩");

        row2.createCell(3).setCellValue("数学成绩");

        row2.createCell(4).setCellValue("英语成绩");

        //在sheet里创建第三行

        HSSFRow row3 = sheet.createRow(2);

        row3.createCell(0).setCellValue("小明");

        row3.createCell(1).setCellValue("1班");

        row3.createCell(2).setCellValue(80);

        row3.createCell(3).setCellValue(75);

        row3.createCell(4).setCellValue(88);

        HSSFRow row4 = sheet.createRow(3);

        row4.createCell(0).setCellValue("小红");

        row4.createCell(1).setCellValue("1班");

        row4.createCell(2).setCellValue(82);

        row4.createCell(3).setCellValue(70);

        row4.createCell(4).setCellValue(90);

        wb.write(response.getOutputStream());
		// 别忘了关流
        wb.close();
    }
HttpServletrequest 与HttpServletResponse区别(<—点击)
response内容类型:

下述为内容格式=>请求体中对应的编码

 	'doc'        => 'application/msword',
    'bin'        => 'application/octet-stream',
    'exe'        => 'application/octet-stream',
    'so'        => 'application/octet-stream',
    'dll'        => 'application/octet-stream',
    'pdf'        => 'application/pdf',
    'ai'        => 'application/postscript',
    'xls'        => 'application/vnd.ms-excel',
    'ppt'        => 'application/vnd.ms-powerpoint',
    'dir'        => 'application/x-director',
    'js'        => 'application/x-javascript',
    'swf'        => 'application/x-shockwave-flash',
    'xhtml'        => 'application/xhtml+xml',
    'xht'        => 'application/xhtml+xml',
    'zip'        => 'application/zip',
    'mid'        => 'audio/midi',
    'midi'        => 'audio/midi',
    'mp3'        => 'audio/mpeg',
    'rm'        => 'audio/x-pn-realaudio',
    'rpm'        => 'audio/x-pn-realaudio-plugin',
    'wav'        => 'audio/x-wav',
    'bmp'        => 'image/bmp',
    'gif'        => 'image/gif',
    'jpeg'        => 'image/jpeg',
    'jpg'        => 'image/jpeg',
    'png'        => 'image/png',
    'css'        => 'text/css',
    'html'        => 'text/html',
    'htm'        => 'text/html',
    'txt'        => 'text/plain',
    'xsl'        => 'text/xml',
    'xml'        => 'text/xml',
    'mpeg'        => 'video/mpeg',
    'mpg'        => 'video/mpeg',
    'avi'        => 'video/x-msvideo',
    'movie'        => 'video/x-sgi-movie',  

到此为止就导出完毕,欣赏一下效果:
在这里插入图片描述
excel内容:
在这里插入图片描述

使用poi按路径导入和基于springboot导入

先展示excel样式:
在这里插入图片描述

先附上Controller类内容:单纯的调用方法

package com.boot.controller;

import com.boot.entity.ExcelImport;
import com.boot.service.ExcelService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Excel Controller
 */
@RestController
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @PostMapping("poiImport")
    public List<ExcelImport> poiImport(@RequestParam("file") MultipartFile file) throws IOException, InvalidFormatException {
        return excelService.poiImport(file.getInputStream());
    }
}

service内容:详细解释在代码注释

@Override
    public List<ExcelImport> poiImport(InputStream in) throws IOException, InvalidFormatException {
        // 可以直接读取路径导入excel
        // File path = new File("E:\\导入.xlsx");
        // XSSFWorkbook sheets = new XSSFWorkbook(path);
        XSSFWorkbook sheets = new XSSFWorkbook(in);
        // 将没有内容的单元格有null转为"",避免空指针的出现
        sheets.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        // 获取第一个sheet
        XSSFSheet sheet0 = sheets.getSheetAt(0);
        // 获取excel有几列,一般第一行为表头,所以获取第一行的列数量接可以了
        int num = sheet0.getRow(0).getPhysicalNumberOfCells();
        List<ExcelImport> list = new ArrayList<>();
        // 循环遍历所有行, i = 1指当前Excel的第二行,第一行为表头不读取
        for (int i = 1; i <= sheet0.getLastRowNum(); i++) {
            XSSFRow row = sheet0.getRow(i);
            // 判断当前行是否有数据
            if (notEmptyRow(row)) {
                ExcelImport excelImport = new ExcelImport();
                // 将当前行的所有单元格内容格式转成String类型
                for (int j = 0; j < num; j++) {
                    row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                }
                excelImport.setName(row.getCell(0).getStringCellValue());
                excelImport.setAge(row.getCell(1).getStringCellValue());
                excelImport.setHobby(row.getCell(2).getStringCellValue());
                list.add(excelImport);
            }
        }
        return list;
    }

	/**
     * 判断当前行是否有值
     *
     * @param row 当前行内容
     * @return boolean
     */
    public boolean notEmptyRow(XSSFRow row) {
        if (row == null || row.toString().isEmpty()) {
            return false;
        } else {
            Iterator<Cell> it = row.iterator();
            boolean isEmpty = true;
            while (it.hasNext()) {
                Cell cell = it.next();
                if (StringUtils.hasText(cell.getStringCellValue().trim())) {
                    isEmpty = false;
                    break;
                }
            }
            return !isEmpty;
        }
    }

导入采用postMan测试,postMan使用教程百度或者请教会使用的人,效果如图
在这里插入图片描述

jxls简单使用

jxls是通过模板导出excel,jxls只做数据填充,样式由模板自定义
先提供jar包
 		<dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls</artifactId>
            <version>2.4.6</version>
            </dependency>
        <dependency>
           <groupId>org.jxls</groupId>
           <artifactId>jxls-poi</artifactId>
           <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-jexcel</artifactId>
            <version>1.0.7</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-core</artifactId>
            <version>1.0.5</version>
        </dependency>
模板样式

在这里插入图片描述解释一下模板表达式:${staffs.name}: ${}固定写法, staffs为java程序map的key, name为字段名, 数据结构见下java程序
如果表达式内的字段名错误或者是一个不存在的字段名,则Java程序会包空指针错误

简单导出
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jxls.transformer.XLSTransformer;

public class JxlsUtils{

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        List<Staff> staffs = new ArrayList<Staff>();

        Staff s1 = new Staff("张三", 6000D, 3000D);
        staffs.add(s1);

        Staff s2 = new Staff("李四", 5000D, 2000D);
        staffs.add(s2);

        Staff s3 = new Staff("王五", 4000D, 1000D);
        staffs.add(s3);

        // 模板位置
        String srcFilePath = "e:/demo.xlsx";
        // 导出路径及文件名
        String destFilePath = "e:/date.xlsx";
        Map<String, List<Staff>> beanParams = new HashMap<String, List<Staff>>();
        beanParams.put("staffs", staffs);

        // 核心两句导出
        XLSTransformer former = new XLSTransformer();
        former.transformXLS(srcFilePath, beanParams, destFilePath);
        System.out.println("大聪明,导出完毕");
    }
}
导出效果

在这里插入图片描述

持续更新~~

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值