JAVA-创建Excel 将List<HashMap<K, V>>写入Excel 转换成excel 读取本地文件excel转字节流转string

博客背景:JAVA项目,将数据库内容读取创建Excel存到指定位置~

一、创建Excel

1、XSSFWorkbook

创建一个工作蒲;

2、XSSFSheet

创建一个表格,可以设置其中的行宽高、字体等等;

3、设定存储位置

positon为文件存储位置,可以直接设置位置为磁盘中指定位置;如下默认为项目运行的上一级目录;

4、所需数据转换

maps是从数据库中取出的List<HashMap<String, Object>>类型的数据;

5、数据赋值

读取maps循环赋值;

6、File、 FileOutputStream

使用File、 FileOutputStream创建excel文件

代码如下:

public void createExcel() {
    
    
        String positon = "../test.xlsx";
        List<HashMap<String, Object>> maps = testMapper.getTestInfo();
        // 定义一个新的工作簿
        XSSFWorkbook wb = new XSSFWorkbook();
        // 创建一个Sheet页,命名为first
        XSSFSheet sheet = wb.createSheet("first");
        //设置行高
        sheet.setDefaultRowHeight((short) (2 * 256));
        //设置列宽
        sheet.setColumnWidth(0, 4000);
        sheet.setColumnWidth(1, 4000);
        sheet.setColumnWidth(2, 4000);
        XSSFFont font = wb.createFont();
        //设置字体
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        //获得表格第一行
        XSSFRow row = sheet.createRow(0);
        //根据需要给第一行每一列设置标题
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("Name");
        cell = row.createCell(1);
        cell.setCellValue("Sex");
        cell = row.createCell(2);
        cell.setCellValue("Age");
        cell = row.createCell(3);
        XSSFRow rows;
        XSSFCell cells;

        //循环拿到的数据给所有行每一列设置对应的值
        for (int i = 0; i < maps.size(); i++) {
    
    
            // 在这个sheet页里创建一行
            rows = sheet.createRow(i + 1);n
            HashMap<String, Object> map = maps.get(i);
            // 该行创建一个单元格,在该单元格里设置值
            String name = map.get("name").toString();
            String sex = map.get("sex").toString();
            Long age = 0L;
            cells = rows.createCell(0);
            cells.setCellValue(taskName);
            cells = rows.createCell(1);
            cells.setCellValue(domain);
            cells = rows.createCell(2);
            cells.setCellValue(age);
        }
        try {
    
    
        	//创建文件的路径
            File file = new File(positon);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            //将创建的表格写入
            wb.write(fileOutputStream);
            wb.close();
            fileOutputStream.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

二、读取文件

读取本地文件,将其转成字节流 , 再转成string格式输出
positon为文件存储位置,可以直接设置位置为磁盘中指定位置;如下默认为项目运行的上一级目录;

代码如下:

String positon =  "../test.xlsx";
//读取文件
InputStream is = new FileInputStream(positon);
int iAvail = is.available();
//转为字节流
byte[] bytes = new byte[iAvail];
is.read(bytes);
//转成string
String table = new String(bytes);

参考:
https://www.cnblogs.com/mythz/p/14177739.html
https://blog.csdn.net/qq_39898191/article/details/104500896

猜你喜欢

转载自blog.csdn.net/weixin_44436677/article/details/128228737
今日推荐