sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::


入门案例:

从Excel文件读取数据

1:新建excel表格(名称:HelloWord):

POI java 对Excel加密 java poi操作excel_List


表格地址:C:\Users\MrFan\Desktop\helloWord.xlsx

2:引入依赖 :

<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>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

代码示例: 读取单元格内容

public static void main(String[] args) throws IOException {
        //根据目录  创建一个工作薄对象
        XSSFWorkbook workbook = new XSSFWorkbook("C:\\Users\\MrFan\\Desktop\\helloWord.xlsx");
        //根据工作薄  获取到工作表  传入工作表的索引 第几个 工作表
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        //根据工作表获取到行
        for (Row row : sheetAt) {
            //获取单元格
            for (Cell cell : row) {
                //获取单元格里的内容
                String stringCellValue = cell.getStringCellValue();
                //打印
                System.out.println(stringCellValue);
            }
        }
}</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li><li>10.</li><li>11.</li><li>12.</li><li>13.</li><li>14.</li><li>15.</li><li>16.</li><li>17.</li></ul></pre></div><div class="toolbar"></div></div></div><p>结果:</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_2" class="copy_btn disable">登录后复制</button> <a title="登录后一键下载全文代码" class="downloadCode"><i class="iconblog blogimport  "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_2">空山

新雨后
天气
晚来秋

  • 1.
  • 2.
  • 3.
  • 4.

代码示例:向单元格里写入

public static void main(String[] args) throws IOException {
//创建工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
//创建工作表,并通过有参的构造方法指定工作表名称
XSSFSheet sheet = workbook.createSheet("诗几句");
//创建行
XSSFRow row = sheet.createRow(0);
//创建单元格,指定索引的方式
row.createCell(0).setCellValue("空山新雨后");
row.createCell(1).setCellValue("天气晚来秋");

    //创建行  第二行
    XSSFRow row1 = sheet.createRow(1);
    //创建单元格,指定索引的方式
    row1.createCell(0).setCellValue("不识南朝今日雨");
    row1.createCell(1).setCellValue("路上行人是几朝");

    //输出流对象
    FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\MrFan\\Desktop\\诗几首.xlsx");
    //调用工作薄的写出方法,并传入流对象
    workbook.write(fileOutputStream);
    //将内容进行刷新,并且释放资源
    fileOutputStream.flush();
    fileOutputStream.close();
    System.out.println("写入成功");

}</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li><li>10.</li><li>11.</li><li>12.</li><li>13.</li><li>14.</li><li>15.</li><li>16.</li><li>17.</li><li>18.</li><li>19.</li><li>20.</li><li>21.</li><li>22.</li><li>23.</li><li>24.</li><li>25.</li><li>26.</li><li>27.</li></ul></pre></div><div class="toolbar"></div></div></div><p>输出示例:</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_4" class="copy_btn disable">登录后复制</button> <a title="登录后一键下载全文代码" class="downloadCode"><i class="iconblog blogimport  "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_4">写入成功</code><ul class="pre-numbering" style=""><li>1.</li></ul></pre></div><div class="toolbar"></div></div></div><p style="text-align:center;"><img src="https://s2.51cto.com/images/blog/202306/16085751_648bb38fa050614964.png?x-oss-process=image/watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=,x-oss-process=image/resize,m_fixed,w_1184/format,webp" alt="POI java 对Excel加密 java poi操作excel_POI java 对Excel加密_02" title="在这里插入图片描述" style="visibility: visible; width: 338px;"></p><p><br></p><p> 实战练习:<br></p><p> 需求<br></p><ol><li>读取excel数据到数据库</li><li>将数据库数据写入excel</li><li>增加样式</li></ol><p>准备工作:<br> 新建一个excel表格</p><blockquote style="margin-top: 5px; margin-bottom: 5px; padding-left: 1em; margin-left: 0px; border-left: 3px solid rgb(238, 238, 238); opacity: 0.6;"><p style="text-align:center;"><img src="https://s2.51cto.com/images/blog/202306/16085751_648bb38f95f1910745.png?x-oss-process=image/watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=,x-oss-process=image/resize,m_fixed,w_1184/format,webp" alt="POI java 对Excel加密 java poi操作excel_apache_03" title="在这里插入图片描述" style="visibility: visible; width: 741px;"></p><p><br></p><p> 创建一个与表格数据一致的实体类</p></blockquote><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_5" class="copy_btn disable">登录后复制</button> <a title="登录后一键下载全文代码" class="downloadCode"><i class="iconblog blogimport  "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_5">//商品表

public class Product {
//商品编号
private Integer pid;
//商品名称
private String pname;
//商品价格
private BigDecimal price;
//商品库存
private Integer pstock;
//get/set方法

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

核心逻辑

package com.itFan.Excel;

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.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ProductExcel {
public static void main(String[] args) throws IOException {
//使用键盘录入白模拟用户操作
Scanner scanner = new Scanner(System.in);
System.out.println("请选择您要进行的操作,1-导入,2-导出");
int num = scanner.nextInt();
if (num == 1) {
//进行导入操作,读取表格中的数据,并写入到数据库
System.out.println("请输入您要读取的文件位置,不包含空格");
String path = scanner.next();
//调用读的方法
List<Product> read = ProductExcel.read(path);
//调用与数据库的对接方法insert,插入数据库 === 自己完成哦

    } else if (num == 2) {
        //进行导出操作,读取数据库中的数据,并写出到表格中
        //1:读取数据  用sql 查出Product对象  是个ProductList集合
        //跟据业务表添加查询逻辑==========自己完成哦
        
        //2:写出表格
        System.out.println("请输入要写入的文档位置");
        String path = scanner.next();
        //调用写的方法
        List&lt;Product&gt; write = write(productList, path);
        System.out.println("数据已经成功从数据库写出到文件");
    }
    }
//读取工作 表的操作
private static List&lt;Product&gt; read(String path) throws IOException {
    //获取工作薄
    XSSFWorkbook workbook = new XSSFWorkbook(path);
    //获取工作表
    XSSFSheet sheetAt = workbook.getSheetAt(0);
    //定义商品返回对象
    ArrayList&lt;Product&gt; products = new ArrayList&lt;&gt;();
    //获取行 先获取行数  进行遍历  表中第一行的表单目录  在数据库中对应字段名  所以不需要读取
    //最后的行数
    int lastRowNum = sheetAt.getLastRowNum();
    for (int i = 1; i &lt; lastRowNum; i++) {
        XSSFRow row = sheetAt.getRow(i);
        if (row != null) {
            //每一行数据就相当于以及各商品对象
            ArrayList&lt;Object&gt; list = new ArrayList&lt;&gt;();
            //获取单元格
            for (Cell cell : row) {
                if (cell != null) {
                    //获取数据
                    //为了防止类型异常,先全部设为String类型
                    cell.setCellType(CellType.STRING);
                    String stringCellValue = cell.getStringCellValue();
                    if (stringCellValue != null &amp;&amp; stringCellValue.trim().length()&gt;0) {
                        list.add(stringCellValue);
                    }
                }
            }
            if (list.size() &gt; 0) {
                //将表里的值 封装给商品对象 赋值给数据库里的值
                products = new Product(Integer.parseInt(list.get(0)), list.get(1), Double.parseDouble(list.get(2)), Integer.parseInt(list.get(3)));
            }
        }
    }
    return products;
}

//写出到excel表中
//读取工作 表的操作
private static List&lt;Product&gt; write(List&lt;Product&gt; productList,String path) throws IOException {
    //创建工作铺
    XSSFWorkbook workbook = new XSSFWorkbook();
    //创建工作表
    XSSFSheet sheet = workbook.createSheet("商品表");
    //创建行
    XSSFRow row = sheet.createRow(0);
    row.createCell(0).setCellValue("商品编号");
    row.createCell(1).setCellValue("商品名称");
    row.createCell(2).setCellValue("商品单价(单位:元/斤)");
    row.createCell(3).setCellValue("商品库存(单位:吨)");
    for (int i = 0; i &lt;productList.size(); i++) {
        //获取每次的行数
        XSSFRow row1 = sheet.createRow(i + 1);
        //给每个单元格赋值
        row1.createCell(0).setCellValue(ProductList.get(i).getPid());
        row1.createCell(1).setCellValue(ProductList.get(i).getPname());
        row1.createCell(2).setCellValue(ProductList.get(i).getPrice());
        row1.createCell(3).setCellValue(ProductList.get(i).getPstock());

    }
  //创建一个文件输出流  将文件输出
    FileOutputStream fileOutputStream = new FileOutputStream(path);
    //写出文件
    workbook.write(fileOutputStream);
    //将流中的数据刷新到磁盘中
    fileOutputStream.flush();
    //释放资源
    fileOutputStream.close();

}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.



原文链接:https://blog.51cto.com/u_16099355/6497287

posted on 2023-10-09 17:48  sunny123456  阅读(323)  评论(0编辑  收藏  举报