国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表

這篇具有很好參考價(jià)值的文章主要介紹了POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

POI

簡(jiǎn)介:

POI是Apache軟件基金會(huì)用Java編寫的免費(fèi)開(kāi)源的跨平臺(tái)的 Java API,Apache POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能。POI為“Poor Obfuscation Implementation”的首字母縮寫,意為“可憐的模糊實(shí)現(xiàn)”。
所以POI的主要功能是可以用Java操作Microsoft Office的相關(guān)文件,但是一般我們都是用來(lái)操作Excel相關(guān)文件。

優(yōu)劣勢(shì):
Jxl:消耗小,圖片和圖形支持有限
Poi:功能更加完善

POI包結(jié)構(gòu)

HSSF:讀寫Microsoft Excel XLS
XSSF:讀寫Microsoft Excel XLSX
HWPF:讀寫Microsoft Word DOC
HSLF:讀寫 Microsoft PowerPoint
本次課主要使用XSSF包下的類
注意:
操作Excel文件區(qū)分版本:
2003版本(包含2003)以前的擴(kuò)展名為.xls需要用HSSFWorkbook類操作
2007版本(包含2007)以后的擴(kuò)展名為.xlsx需要用XSSFWorkbook類操作

POI入門案例

  • XSSFWorkbook:工作簿
  • XSSFSheet:工作表
  • Row:行
  • Cell:?jiǎn)卧?/li>

從Excel文件中讀取數(shù)據(jù)

  1. 獲取工作簿
  2. 獲取工作表
  3. 遍歷工作表,獲取行對(duì)象
  4. 便利行對(duì)象,過(guò)去單元格對(duì)象
  5. 獲的單元格的值

導(dǎo)入poi相關(guān)的依賴

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

編寫Java代碼

package com.aaa.read;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 19:38
 * @description :從Excel文件中讀取數(shù)據(jù)
 */
public class Demo1 {
    public static void main(String[] args) throws IOException {
        //獲取工作簿
        XSSFWorkbook workbook = new XSSFWorkbook("E:\\mind\\poi\\student.xlsx");
        //獲取工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        //獲取行
        for (Row row : sheet) {
            //獲取單元格
            for (Cell cell : row) {
                //設(shè)置單元格的數(shù)據(jù)類型
                cell.setCellType(CellType.STRING);
                System.out.println(cell.getStringCellValue());
            }
        }
    }
}

普通for循環(huán)

package com.aaa.read;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 19:38
 * @description :
 */
public class Demo1 {
    public static void main(String[] args) throws IOException {
        //獲取工作簿
        XSSFWorkbook workbook = new XSSFWorkbook("E:\\mind\\poi\\student.xlsx");
        //獲取工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        //獲取行
        /*for (Row row : sheet) {
            //獲取單元格
            for (Cell cell : row) {
                //設(shè)置單元格的數(shù)據(jù)類型
                cell.setCellType(CellType.STRING);
                System.out.println(cell.getStringCellValue());
            }
        }*/
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);
            if (row!=null){
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    //獲取單元格
                    XSSFCell cell = row.getCell(j);
                    if (cell!=null){
                        //設(shè)置單元格的數(shù)據(jù)類型
                        cell.setCellType(CellType.STRING);
                        System.out.println(cell);
                    }
                }
            }

        }
        //釋放資源
        workbook.close();
    }
}

測(cè)試結(jié)果:
測(cè)試的時(shí)候一定把要操作的表關(guān)閉,否則兩個(gè)進(jìn)程都要讀這個(gè)文件就會(huì)報(bào)下面的錯(cuò)

Exception in thread “main” java.io.FileNotFoundException: E:\mind\poi\student.xlsx (另一個(gè)程序正在使用此文件,進(jìn)程無(wú)法訪問(wèn)。)

正常情況:
POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表

向Excel文件中寫入數(shù)據(jù)

  1. 創(chuàng)建一個(gè)Excel表格
  2. 創(chuàng)建工作表
  3. 創(chuàng)建行
  4. 創(chuàng)建單元格賦值
  5. 通過(guò)輸出流將對(duì)象下載到磁盤

編寫Java代碼

package com.aaa.write;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 20:13
 * @description :
 * 1. 創(chuàng)建一個(gè)Excel表格
 * 2. 創(chuàng)建工作表
 * 3. 創(chuàng)建行
 * 4. 創(chuàng)建單元格賦值
 * 5. 通過(guò)輸出流將對(duì)象下載到磁盤
 */
public class Demo2 {
    public static void main(String[] args) throws IOException {
        //1. 創(chuàng)建一個(gè)Excel表格
        XSSFWorkbook workbook = new XSSFWorkbook();
        //2. 創(chuàng)建工作表
        XSSFSheet sheet = workbook.createSheet("工作表一");
        //3. 創(chuàng)建行
        XSSFRow row1 = sheet.createRow(0);
        //4. 創(chuàng)建單元格賦值
        XSSFCell cell1 = row1.createCell(0);
        cell1.setCellValue("陳嬌花");
        XSSFCell cell2 = row1.createCell(1);
        cell2.setCellValue("趙鐵牛 ");
        XSSFRow row2 = sheet.createRow(1);
        XSSFCell cell21 = row2.createCell(0);
        cell21.setCellValue("陳嬌花");
        XSSFCell cell22 = row2.createCell(1);
        cell22.setCellValue("趙鐵牛");

        //5. 通過(guò)輸出流將對(duì)象下載到磁盤
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\mind\\poi\\aaa.xlsx");
        workbook.write(fileOutputStream);
        //刷新輸出流
        fileOutputStream.flush();
        //6. 釋放資源
        fileOutputStream.close();
        workbook.close();
    }
}

執(zhí)行結(jié)果:
POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表

將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù)

導(dǎo)入數(shù)據(jù)庫(kù)連接相關(guān)的jar包

        <!--阿里巴巴數(shù)據(jù)源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.11</version>
        </dependency>
        <!--MySQL連接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>

配置MybatisConfig.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/poidemo?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.aaa.dao"/>
    </mappers>
</configuration>

編寫實(shí)體類

package com.aaa.domain;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 20:56
 * @description :
 */
public class Product {
    Integer id;
    String name;
    Double price;
    Integer pstock;
    //省略get,set方法,全參構(gòu)造器,無(wú)參構(gòu)造器,toString方法
    //大家寫的時(shí)候記得寫上
}

操作類
獲取工作簿
過(guò)去工作表
獲取最后一行的行號(hào)
排除第一行
將每一行封裝到一個(gè)list中
設(shè)置單元格類型
將每一行的內(nèi)容封裝為一個(gè)實(shí)體類
將每一個(gè)實(shí)體類加入到productList中
關(guān)閉資源

package com.aaa.web;

import com.aaa.domain.Product;
import com.aaa.service.ProductService;
import com.aaa.service.impl.ProductServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 20:48
 * @description : 將Excel表中的數(shù)據(jù)添加到數(shù)據(jù)庫(kù)
 */
public class InsertDB {
    public static void main(String[] args) throws IOException {
        ProductService productService = new ProductServiceImpl();
        //Scanner輸入文件地址
        Scanner scanner = new Scanner(System.in);
        System.out.println("請(qǐng)輸入文件地址(不包含空格)");
        String path = scanner.nextLine();
        //調(diào)用getObjList方法,得到Product的list集合
        List<Product> objList = getObjList(path);
        System.out.println(objList);
        //插入數(shù)據(jù)庫(kù)
        Integer save = productService.save(objList);
        System.out.println("成功插入"+save+"條數(shù)據(jù)");
    }

    /**
     * 傳入文件地址,返回list集合
     * @param path
     * @return
     * @throws IOException
     */
    public static List<Product> getObjList(String path) throws IOException {
        List<Product> productList = new ArrayList<>();
        //獲取工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(path);
        //過(guò)去工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        //獲取最后一行的行號(hào)
        int lastRowNum = sheet.getLastRowNum();
        //排除第一行
        for (int i = 1; i <= lastRowNum; i++) {
            //獲取每一行
            XSSFRow row = sheet.getRow(i);
            if (row!=null){
                //將每一行封裝到一個(gè)list中
                List<String> list = new ArrayList<>();
                for (Cell cell : row) {
                    if (cell!=null){
                        //設(shè)置單元格類型
                        cell.setCellType(CellType.STRING);
                        String value = cell.getStringCellValue();
                        list.add(value);
                    }
                }
                //將每一行的內(nèi)容封裝為一個(gè)實(shí)體類
                Product  product = new Product(Integer.parseInt(list.get(0)),list.get(1),Double.parseDouble(list.get(2)),Integer.parseInt(list.get(3)));
                //將每一個(gè)實(shí)體類加入到productList中
                productList.add(product);
            }
        }
        //關(guān)閉資源
        workbook.close();
        return productList;
    }
}

service層接口

package com.aaa.service;

import com.aaa.domain.Product;

import java.util.List;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 21:26
 * @description :
 */
public interface ProductService {
    Integer save(List<Product> list);
}

service層實(shí)現(xiàn)類

package com.aaa.service.impl;

import com.aaa.dao.ProductDao;
import com.aaa.domain.Product;
import com.aaa.service.ProductService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 21:27
 * @description :
 */
public class ProductServiceImpl implements ProductService {
    //mybatis配置文件的路徑
    String resource = "MybatisConfig.xml";
    InputStream inputStream;
    {
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //得到SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    /**
     * 添加方法
     * @param product
     * @return
     */
    @Override
    public Integer save(List<Product> product) {
        //開(kāi)啟SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取代理對(duì)象
        ProductDao productDao1 = sqlSession.getMapper(ProductDao.class);
        int i = 0;
        for (Product product1 : product) {
            //插入數(shù)據(jù)
            Integer save = productDao1.save(product1);
            if (save!=null){
                i = i+save;
            }
            sqlSession.commit();
        }
        sqlSession.close();
        return i;
    }
}

dao接口

package com.aaa.dao;

import com.aaa.domain.Product;

import java.util.List;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 21:28
 * @description :
 */
public interface ProductDao {
    Integer save(Product product);
}

mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.dao.ProductDao">

    <insert id="save">
        insert into product (id,name,price,pstock) values
                    (#{id},#{name},#{price},#{pstock})
    </insert>
</mapper>

運(yùn)行InsertDB.class
POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表

將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表

編寫操作類

新建工作簿
新建工作表
第一行,表頭
將每條list中的商品寫入工作表中,從第二行開(kāi)始,第一行,表頭
獲取文件輸出流
工作簿寫入
刷新輸出流
關(guān)閉資源

package com.aaa.web;

import com.aaa.domain.Product;
import com.aaa.service.ProductService;
import com.aaa.service.impl.ProductServiceImpl;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 23:07
 * @description : 將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表
 */
public class InsertExcel {
    public static void main(String[] args) throws IOException {
        ProductService productService = new ProductServiceImpl();
        //查詢所有
        List<Product> productList = productService.getAll();
        System.out.println(productList);
        //輸入路徑
        Scanner scanner = new Scanner(System.in);
        System.out.println("請(qǐng)輸入文件的輸出路徑");
        String path = scanner.nextLine();
        //調(diào)用getWorkbook方法
        InsertExcel.getWorkbook(productList, path);
        //如果執(zhí)行成功打印
        System.out.println("操作成功");
    }

    /**
     * 將數(shù)據(jù)庫(kù)中的數(shù)據(jù),寫入Excel文件中
     * @param productList
     * @param path
     * @throws IOException
     */
    public static void getWorkbook(List<Product> productList,String path) throws IOException {
        //新建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //新建工作表
        XSSFSheet sheet = workbook.createSheet("商品表");
        //第一行,表頭
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("商品編號(hào)");
        XSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("商品名稱");
        XSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("商品價(jià)格(單位:元/斤)");
        XSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("商品庫(kù)存(單位:噸)");
        //將每條list中的商品寫入工作表中,從第二行開(kāi)始,第一行,表頭
        for (int i = 1; i <= productList.size(); i++) {
            //獲取product(注意是i-1)
            Product product = productList.get(i-1);
            //插入數(shù)據(jù)
            XSSFRow row1 = sheet.createRow(i);
            XSSFCell cell4 = row1.createCell(0);
            cell4.setCellValue(product.getId());
            XSSFCell cell5 = row1.createCell(1);
            cell5.setCellValue(product.getName());
            XSSFCell cell6 = row1.createCell(2);
            cell6.setCellValue(product.getPrice());
            XSSFCell cell7 = row1.createCell(3);
            cell7.setCellValue(product.getPstock());
        }
        //獲取文件輸出流
        FileOutputStream fos = new FileOutputStream(path);
        //工作簿寫入
        workbook.write(fos);
        //刷新輸出流
        fos.flush();
        //關(guān)閉資源
        fos.close();
        workbook.close();
    }
}

service接口

package com.aaa.service;

import com.aaa.domain.Product;

import java.util.List;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 21:26
 * @description :
 */
public interface ProductService {
    /**
     * 插入數(shù)據(jù)
     * @param list
     * @return
     */
    Integer save(List<Product> list);

    /**
     * 查詢所有
     * @return
     */
    List<Product> getAll();
}

service實(shí)現(xiàn)類

package com.aaa.service.impl;

import com.aaa.dao.ProductDao;
import com.aaa.domain.Product;
import com.aaa.service.ProductService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 21:27
 * @description :
 */
public class ProductServiceImpl implements ProductService {
    //mybatis配置文件的路徑
    String resource = "MybatisConfig.xml";
    InputStream inputStream;
    {
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //得到SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    /**
     * 添加方法
     * @param
     * @return
     */
    @Override
    public Integer save(List<Product> productList) {
        //開(kāi)啟SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取代理對(duì)象
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        int i = 0;
        for (Product product : productList) {
            //插入數(shù)據(jù)
            Integer save = productDao.save(product);
            if (save!=null){
                i = i+save;
            }
            sqlSession.commit();
        }
        sqlSession.close();
        return i;
    }

    /**
     * 查詢所有
     * @return List<Product>
     */
    @Override
    public List<Product> getAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取代理對(duì)象
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        //關(guān)閉資源
        List<Product> productList = productDao.getAll();
        sqlSession.close();
        return productList;
    }
}

dao接口

package com.aaa.dao;

import com.aaa.domain.Product;

import java.util.List;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 21:28
 * @description :
 */
public interface ProductDao {
    Integer save(Product product);

    List<Product> getAll();
}

mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.dao.ProductDao">

    <insert id="save">
        insert into product (id,name,price,pstock) values
                    (#{id},#{name},#{price},#{pstock})
    </insert>
    <select id="getAll" resultType="com.aaa.domain.Product">
        select *
        from product;
    </select>
</mapper>

運(yùn)行InsertExcel.class
POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表

設(shè)置樣式

在Demo2中基礎(chǔ)上

package com.aaa.write;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author : 尚騰飛
 * @version : 1.0
 * @createTime : 2022/9/26 20:13
 * @description :
 * 1. 創(chuàng)建一個(gè)Excel表格
 * 2. 創(chuàng)建工作表
 * 3. 創(chuàng)建行
 * 4. 創(chuàng)建單元格賦值
 * 5. 通過(guò)輸出流將對(duì)象下載到磁盤
 */
public class Demo2 {
    public static void main(String[] args) throws IOException {
        //1. 創(chuàng)建一個(gè)Excel表格
        XSSFWorkbook workbook = new XSSFWorkbook();
        //2. 創(chuàng)建工作表
        XSSFSheet sheet = workbook.createSheet("工作表一");
        
        //單元格樣式
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //字體樣式
        XSSFFont font = workbook.createFont();
        font.setFontName("宋體");
        font.setColor(IndexedColors.PINK.getIndex());
        cellStyle.setFont(font);

        //3. 創(chuàng)建行
        XSSFRow row1 = sheet.createRow(0);
        //4. 創(chuàng)建單元格賦值
        XSSFCell cell1 = row1.createCell(0);
        cell1.setCellStyle(cellStyle);
        cell1.setCellValue("陳嬌花");
        XSSFCell cell2 = row1.createCell(1);
        cell2.setCellStyle(cellStyle);
        cell2.setCellValue("趙鐵牛 ");
        XSSFRow row2 = sheet.createRow(1);
        XSSFCell cell21 = row2.createCell(0);
        cell21.setCellValue("陳嬌花");
        XSSFCell cell22 = row2.createCell(1);
        cell22.setCellValue("趙鐵牛");

        //5. 通過(guò)輸出流將對(duì)象下載到磁盤
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\mind\\poi\\aaa.xlsx");
        workbook.write(fileOutputStream);
        //刷新輸出流
        fileOutputStream.flush();
        //6. 釋放資源
        fileOutputStream.close();
        workbook.close();
    }
}

測(cè)試結(jié)果:
POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表
全文參考的下面教程:視頻特點(diǎn)人美聲甜,年輕貌美
Java教程使用POI讀取excel文檔
https://www.bilibili.com/video/BV1bJ411G7Aw?p=1&vd_source=0eeffffe21421dad257058d19ad2f1d2

EasyPoi

But

apache的缺點(diǎn)

但是apache存在一些缺點(diǎn)

  1. 對(duì)于復(fù)雜的Excel模板樣式需要編寫大量的代碼實(shí)現(xiàn)
  2. 大數(shù)據(jù)量的讀取/導(dǎo)成效率低下,甚至可能內(nèi)存溢出

為了解決上述poi的缺點(diǎn),國(guó)內(nèi)有很多開(kāi)源項(xiàng)目對(duì)poi進(jìn)行了封裝,大大減少代碼量,使其能夠更簡(jiǎn)單的被我們使用并提高開(kāi)發(fā)效率,例如EasyPoi,Excel4J,HuTools等優(yōu)秀的開(kāi)源項(xiàng)目。我們這次以EasyPoi為例

easypoi功能如同名字easy,主打的功能就是容易,讓一個(gè)沒(méi)見(jiàn)接觸過(guò)poi的人員就可以方便的寫出Excel導(dǎo)出,Excel模板導(dǎo)出,Excel導(dǎo)入,Word模板導(dǎo)出,通過(guò)簡(jiǎn)單的注解和模板語(yǔ)言(熟悉的表達(dá)式語(yǔ)法),完成以前復(fù)雜的寫法。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-498905.html

使用EasyPoi

1. 導(dǎo)入jar

  1. SpringBoot
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-spring-boot-starter -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>
  1. 普通maven項(xiàng)目
        <!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-base -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.4.0</version>
        </dependency>

2. 編寫實(shí)體類

package com.aaa.domain;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.util.Date;

/**
 * @author : 尚騰飛(838449693@qq.com)
 * @version : 1.0
 * @createTime : 2022/10/8 20:01
 * @description :
 */
@Data
public class Userinfo {
    @Excel(name = "id")
    private Integer id;
    @Excel(name = "用戶名")
    private String username;
    @Excel(name = "密碼")
    private String password;
    @Excel(name = "手機(jī)號(hào)")
    private String phone;
    @Excel(name = "部門編號(hào)")
    private Integer deptid;
    @Excel(name = "頭像")
    private String avatar;
    @Excel(name = "創(chuàng)建時(shí)間" ,format = "yyyy-MM-dd HH:mm:ss")
    private Date createtime;
}

3. 編寫service,controller

package com.aaa.web;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.aaa.domain.Userinfo;
import com.aaa.service.impl.UserinfoServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @author : 尚騰飛(838449693@qq.com)
 * @version : 1.0
 * @createTime : 2022/10/8 20:45
 * @description :
 */
public class EasyPoiController {
    public static void main(String[] args) throws  Exception {
        UserinfoServiceImpl userinfoService = new UserinfoServiceImpl();
        List<Userinfo> userinfoList = userinfoService.findAll();
        System.out.println(userinfoList);
        ExportParams exportParams = new ExportParams("員工表", "員工表", ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Userinfo.class, userinfoList);
        FileOutputStream fos = new FileOutputStream(new File("E:\\mind\\poi\\userinfo.xlsx"));
        workbook.write(fos);
        //刷新輸出流
        fos.flush();
        //關(guān)閉資源
        fos.close();
        workbook.close();
    }
}

到了這里,關(guān)于POI:從Excel文件中讀取數(shù)據(jù),向Excel文件中寫入數(shù)據(jù),將Excel表格中的數(shù)據(jù)插入數(shù)據(jù)庫(kù),將數(shù)據(jù)庫(kù)中的數(shù)據(jù)添加到Excel表的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Python讀取寫入數(shù)據(jù)到Excel文件

    Python讀取寫入數(shù)據(jù)到Excel文件

    【Linux干貨教程】Ubuntu Linux 換源詳細(xì)教程 大家好,我是洲洲,歡迎關(guān)注,一個(gè)愛(ài)聽(tīng)周杰倫的程序員。關(guān)注公眾號(hào)【程序員洲洲】即可獲得10G學(xué)習(xí)資料、面試筆記、大廠獨(dú)家學(xué)習(xí)體系路線等…還可以加入技術(shù)交流群歡迎大家在CSDN后臺(tái)私信我! Hello,各位看官老爺們好,洲洲已

    2024年02月12日
    瀏覽(97)
  • Python讀取excel文件往Elasticsearch數(shù)據(jù)插入時(shí)遇到的問(wèn)題

    Python讀取excel文件往Elasticsearch數(shù)據(jù)插入時(shí)遇到的問(wèn)題

    背景:需要完成一個(gè)功能,使用python讀取一個(gè)excel文件進(jìn)行讀取數(shù)據(jù),然后將這些數(shù)據(jù)直接保存到Elasticsearch中。 用到的工具:python、Elasticsearch 一、問(wèn)題描述 在將項(xiàng)目部署到甲方的時(shí)候,出現(xiàn)用戶導(dǎo)入文件無(wú)法進(jìn)行正常插入到Elasticsearch中的情況,當(dāng)時(shí)看的服務(wù)器的日志,報(bào)

    2023年04月09日
    瀏覽(21)
  • python讀取表格數(shù)據(jù)將pdf文件轉(zhuǎn)excel文件最新可用方法

    python讀取表格數(shù)據(jù)將pdf文件轉(zhuǎn)excel文件最新可用方法

    【ptf】 【轉(zhuǎn)換后Excel】 可用看到表格內(nèi)容位置一致,轉(zhuǎn)換完成 (1)安裝camelot庫(kù) (2)轉(zhuǎn)換代碼

    2024年02月15日
    瀏覽(25)
  • java通過(guò)poi讀取excel中的日期類型

    Java 讀取Excel表格日期類型數(shù)據(jù)的時(shí)候,讀出來(lái)的是這樣的 12-十月-2020,而Excel中輸入的是 2020/10/12 或 2020-10-12 poi處理excel時(shí),當(dāng)excel沒(méi)有明確指明是哪個(gè)類型的數(shù)據(jù)時(shí),poi很可能處理單元格的日期數(shù)據(jù)時(shí)就有可能是一串?dāng)?shù)字,而使用java程序基本無(wú)法轉(zhuǎn)換。 Excel數(shù)據(jù)處理: Exc

    2024年02月15日
    瀏覽(27)
  • c#關(guān)于文件夾/文件/文本讀取遍歷,寫入還有表格的讀取的一些方法

    c#關(guān)于文件夾/文件/文本讀取遍歷,寫入還有表格的讀取的一些方法

    c#遍歷文件夾下的各種文件 將一些log寫入到文本文件中: fs.Seek(offset, whence);移動(dòng)文件讀取的指針到指定位置 offset:開(kāi)始的偏移量,也就是代表需要移動(dòng)偏移的字節(jié)數(shù) whence:給offset參數(shù)一個(gè)定義,表示要從哪個(gè)位置開(kāi)始偏移;0代表從文件開(kāi)頭開(kāi)始算起,1代表從當(dāng)前位置開(kāi)始

    2024年02月01日
    瀏覽(28)
  • 【Python筆記】Python + xlrd + pymysql讀取excel文件數(shù)據(jù)并且將數(shù)據(jù)插入到MySQL數(shù)據(jù)庫(kù)里面

    【Python筆記】Python + xlrd + pymysql讀取excel文件數(shù)據(jù)并且將數(shù)據(jù)插入到MySQL數(shù)據(jù)庫(kù)里面

    這篇文章,主要介紹Python + xlrd + pymysql讀取excel文件數(shù)據(jù)并且將數(shù)據(jù)插入到MySQL數(shù)據(jù)庫(kù)里面。 目錄 一、Python讀取excel 1.1、安裝xlrd庫(kù) 1.2、打開(kāi)excel工作簿 1.3、獲取sheet工作表 1.4、操作row數(shù)據(jù)行 1.5、操作column數(shù)據(jù)列 1.6、操作單元格 二、讀取excel數(shù)據(jù)保存到MySQL 2.1、完整代碼 2.

    2024年02月15日
    瀏覽(27)
  • Matlab:將數(shù)據(jù)寫入 Excel 電子表格

    要將工作區(qū)中的表導(dǎo)出到 Microsoft? Excel? 電子表格文件中,請(qǐng)使用 writetable 函數(shù)。您可以將工作區(qū)中的數(shù)據(jù)導(dǎo)出到文件中的任何工作表,以及導(dǎo)出到該工作表中的任何位置。默認(rèn)情況下,writetable 將表數(shù)據(jù)寫入到文件中的第一張工作表,并從單元格 A1 處開(kāi)始。 例如,創(chuàng)建一個(gè)

    2024年02月09日
    瀏覽(28)
  • 將R語(yǔ)言中的表格數(shù)據(jù)輸出為Excel文件

    將R語(yǔ)言中的表格數(shù)據(jù)輸出為Excel文件 在R語(yǔ)言中,我們可以使用各種方法將表格數(shù)據(jù)輸出為Excel文件。Excel文件是一種常用的電子表格格式,它在數(shù)據(jù)分析和可視化方面具有廣泛的應(yīng)用。本文將介紹幾種常用的方法來(lái)實(shí)現(xiàn)這個(gè)目標(biāo),并提供相應(yīng)的源代碼示例。 方法一:使用 w

    2024年02月07日
    瀏覽(41)
  • ArrayList/MySQL數(shù)據(jù)批量寫入Excel表格

    ArrayList/MySQL數(shù)據(jù)集合寫入Excel 1.文章概述: 寫入 Excel 文件通常需要使用一些庫(kù)或工具,而\\\"EasyExcel\\\"通常是指的阿里巴巴開(kāi)源的EasyExcel庫(kù)。這個(gè)庫(kù)可以讓我們?cè)贘ava中簡(jiǎn)便地進(jìn)行Excel文件的讀寫操作。 2.導(dǎo)入配置: 3.Excel模板類 4.工具類示例代碼:

    2024年02月09日
    瀏覽(18)
  • [excel與dict] python 讀取excel內(nèi)容并放入字典、將字典內(nèi)容寫入 excel文件

    一 讀取excel內(nèi)容、并放入字典 1 讀取excel文件 2 讀取value,舍棄行號(hào) 3 讀取為字典 一 讀取excel內(nèi)容、并放入字典(完整代碼) 二、將字典內(nèi)容寫入 excel文件 1 假設(shè)已有字典內(nèi)容為: 即student列表里有4個(gè)字典, 第一個(gè)字典里面有3對(duì)key-value \\\"num\\\": 1, \\\"name\\\": \\\"cod1\\\", \\\"wfm\\\": 0.1 2 導(dǎo)入Workb

    2024年02月04日
    瀏覽(31)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包