Apache POI入门学习

Apache POI入门学习

    • 官网地址
  • excel中使用到的类
  • 读取excel表格内容
    • 表格内容
    • maven依赖
    • 方式一
      • 测试结果
    • 方式二
      • 测试结果
  • 向excel中写入数据
    • 方式一
    • 方式二
    • 方式三
    • 测试结果
  • 从 Excel 工作表中的公式单元格读取数据
    • 测试结果
  • Excel 工作表中写入公式单元格
  • 从受密码保护的Excel中读取数据
    • 方式一
      • 测试结果
    • 方式二
      • 测试结果
  • 填充背景色和前景色到单元格中
    • 测试结果
  • 将HashMap格式写入表格
    • 测试结果
  • 从excel中读取数据到HashMap中
    • 测试结果
  • 从数据库中读取数据并写入Excel
    • 测试结果
  • 从Excel中读取数据并写入数据库表
    • excel内容
    • 生成的数据表
  • Selenium中的数据驱动测试
    • maven依赖
    • 获取提交按钮的Xpath
    • 工具类
    • 案例代码
  • 在Selenium中将WebTable数据写入Excel表(网页数据抽取)
    • 测试结果
  • 在Excel中单元格内容为日期格式
    • 测试结果
  • 代码地址

官网地址

https://poi.apache.org/index.html
Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。

excel中使用到的类

一个excel表格文件包含一个工作簿,一个工作簿包含多个工作表,每个工作表包含多个行,每行包含多个单元格。
在这里插入图片描述

读取excel表格内容

表格内容

在这里插入图片描述

maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.example</groupId>
    <artifactId>ApachePoi-Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--poi 是基础依赖,提供了操作 Excel 文件的核心功能-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.5</version>
        </dependency>
        <!--poi-ooxml 是操作 Office Open XML 格式文件(如 .xlsx、.docx 等)的扩展库。-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.5</version>
        </dependency>
        <!--spring web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--spring boot单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>3.1.2</version>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

方式一

for循环的方式读取数据

package com.apache.poi.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.poi.ss.usermodel.CellType;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
public class DemoController {

    @PostMapping(value = "/poi/excel/import")
    public void excelImport(@RequestParam("file") MultipartFile file) throws Exception {
        // 输入流
        InputStream inputStream = file.getInputStream();
        // 创建一个工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        // 获取工作表getSheetAt,索引从0开始表示第一个工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 获取工作表中对应的行数
        int rows = sheet.getLastRowNum();
        for (int r = 0; r <= rows; r++) {
            // 获取指定的行
            XSSFRow row = sheet.getRow(r);
            // 获取指定的行数所对应的单元格
            int cols = sheet.getRow(r).getLastCellNum();
            for (int c = 0; c < cols; c++) {
                // 获取指定行指定的单元格
                XSSFCell cell = row.getCell(c);
                // 单元格类型,可以是字符串也可以是数字,也可以是布尔值
                CellType cellType = cell.getCellType();
                switch (cellType) {
                    case STRING -> {
                        // 字符串类型获取对应的字符串值
                        System.out.print(cell.getStringCellValue());
                        break;
                    }
                    case NUMERIC -> {
                        // 数字类型获取对应的数字
                        System.out.print(cell.getNumericCellValue());
                        break;
                    }
                    case BOOLEAN -> {
                        // 布尔类型获取对应的布尔值
                        System.out.print(cell.getBooleanCellValue());
                        break;
                    }
                }
                System.out.print(" | ");
            }
            System.out.println();
        }
    }
}


测试结果

在这里插入图片描述
在这里插入图片描述

方式二

使用Iterator进行遍历表格数据

package com.apache.poi.demo.controller;

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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Iterator;

@RestController
public class DemoTwoController {

    @PostMapping(value = "/poi/excel/import2")
    public void excelImportTwo(@RequestParam("file") MultipartFile file) throws Exception {
        // 输入流
        InputStream inputStream = file.getInputStream();
        // 创建一个工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        // 获取工作表getSheetAt,索引从0开始表示第一个工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.rowIterator();
        while (rowIterator.hasNext()) {
            // 获取指定的行
            XSSFRow row = (XSSFRow) rowIterator.next();
            // 获取单元格
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                XSSFCell cell = (XSSFCell) cellIterator.next();
                CellType cellType = cell.getCellType();
                switch (cellType) {
                    // 字符串类型获取对应的字符串值
                    case STRING -> System.out.print(cell.getStringCellValue());
                    // 数字类型获取对应的数字
                    case NUMERIC -> System.out.print(cell.getNumericCellValue());
                    //布尔类型获取对应的布尔值
                    case BOOLEAN -> System.out.print(cell.getBooleanCellValue());
                }
                System.out.print(" | ");
            }
            System.out.println();
        }
    }
}

测试结果

在这里插入图片描述
在这里插入图片描述

向excel中写入数据

方式一

通过使用for循环的方式向excel中写入数据

package com.apache.poi.demo;

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

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

/**
 * 向excel中写入数据的步骤
 * Workbook -> Sheet -> Rows -> Cells
 */
public class WriteExcelDemo {
    public static void main(String[] args) throws IOException {
        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 工作表名称为Emp Info
        XSSFSheet sheet = workbook.createSheet("Emp Info");
        Object empdata[][] = {
                {"EmpID", "Name", "Job"},
                {101, "David", "Enginner"},
                {102, "Smith", "Manager"},
                {103, "Scott", "Analyst"}
        };
        for (int r = 0; r < empdata.length; r++) {
            // 创建表格行
            XSSFRow row = sheet.createRow(r);
            for (int c = 0; c < empdata[r].length; c++) {
                // 创建单元格
                Cell cell = row.createCell(c);
                Object value = empdata[r][c];
                // 判断值的类型,然后进行转换
                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Integer) {
                    cell.setCellValue((Integer) value);
                } else if (value instanceof Boolean) {
                    cell.setCellValue((Boolean) value);
                }
            }
        }
        File dir = new File(".\\datafiles");
        if (!dir.exists()) {
            // 文件夹不存在则自动创建
            dir.mkdir();
        }
        String filePath = ".\\datafiles\\employee.xlsx";
        // new FileOutputStream(filePath, true);true表示文件不存在时候,自动生成
        FileOutputStream fileOutputStream = new FileOutputStream(filePath, true);
        workbook.write(fileOutputStream);

        // 关闭流
        workbook.close();
        fileOutputStream.close();
        System.out.println("employee.xlsx写入成功");
    }
}

方式二

package com.apache.poi.demo;

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.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 向excel中写入数据的步骤
 * Workbook -> Sheet -> Rows -> Cells
 */
public class WriteExcelDemo2 {
    public static void main(String[] args) throws IOException {
        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 工作表名称为Emp Info
        XSSFSheet sheet = workbook.createSheet("Emp Info");
        Object empdata[][] = {
                {"EmpID", "Name", "Job"},
                {101, "David", "Enginner"},
                {102, "Smith", "Manager"},
                {103, "Scott", "Analyst"}
        };
        int rowCount = 0;
        // 数据存储在一维数组emp[]中,
        for (Object emp[] : empdata) {
            // rowCount++,每次值使用之后,自动加1
            XSSFRow row = sheet.createRow(rowCount++);
            int columnCount = 0;
            for (Object value : emp) {
                XSSFCell cell = row.createCell(columnCount++);
                // 判断值的类型,然后进行转换
                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Integer) {
                    cell.setCellValue((Integer) value);
                } else if (value instanceof Boolean) {
                    cell.setCellValue((Boolean) value);
                }
            }
        }

        File dir = new File(".\\datafiles");
        if (!dir.exists()) {
            // 文件夹不存在则自动创建
            dir.mkdir();
        }
        // 写入当前项目下的datafiles目录下的employee.xlsx
        String filePath = ".\\datafiles\\employee.xlsx";
        // new FileOutputStream(filePath, true);true表示文件不存在时候,自动生成
        FileOutputStream fileOutputStream = new FileOutputStream(filePath, true);
        workbook.write(fileOutputStream);

        // 关闭流
        workbook.close();
        fileOutputStream.close();
        System.out.println("employee.xlsx写入成功");
    }
}

方式三

package com.apache.poi.demo;

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.ArrayList;

/**
 * 向excel中写入数据的步骤
 * Workbook -> Sheet -> Rows -> Cells
 */
public class WriteExcelDemo3 {
    public static void main(String[] args) throws IOException {
        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();

        // 工作表名称为Emp Info
        XSSFSheet sheet = workbook.createSheet("Emp Info");

        ArrayList<Object[]> empData = new ArrayList<>();
        empData.add(new Object[]{"EmpID", "Name", "Job"});
        empData.add(new Object[]{101, "David", "Enginner"});
        empData.add(new Object[]{102, "Smith", "Manager"});
        empData.add(new Object[]{103, "Scott", "Analyst"});


        int rowNum = 0;
        for (Object[] emp : empData) {
            XSSFRow row = sheet.createRow(rowNum++);
            int cellNum = 0;
            for (Object value : emp) {
                XSSFCell cell = row.createCell(cellNum++);
                // 判断值的类型,然后进行转换
                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Integer) {
                    cell.setCellValue((Integer) value);
                } else if (value instanceof Boolean) {
                    cell.setCellValue((Boolean) value);
                }
            }
        }

        // 写入当前项目下的datafiles目录下的employee.xlsx
        String filePath = ".\\datafiles\\employee.xlsx";
        // new FileOutputStream(filePath, true);true表示文件不存在时候,自动生成
        FileOutputStream fileOutputStream = new FileOutputStream(filePath, true);
        workbook.write(fileOutputStream);

        // 关闭流
        workbook.close();
        fileOutputStream.close();
        System.out.println("employee.xlsx写入成功");
    }
}

测试结果

方式一、方式二和方式三的代码,都会在项目的根目录下的datafiles文件夹中生成employee.xlsx
在这里插入图片描述
employee.xlsx的文件内容如下
在这里插入图片描述

从 Excel 工作表中的公式单元格读取数据

package com.apache.poi.demo;

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.FileInputStream;
import java.io.IOException;

public class ReadDataFromFormulaCell {
    public static void main(String[] args) throws IOException {
        String filePath = ".\\datafiles\\readFormula.xlsx";
        FileInputStream fileInputStream = new FileInputStream(filePath);

        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);

        int rows = sheet.getLastRowNum();
        int cols = sheet.getRow(0).getLastCellNum();

        for (int r = 0; r <= rows; r++) {
            XSSFRow row = sheet.getRow(r);
            for (int c = 0; c < cols; c++) {
                XSSFCell cell = row.getCell(c);
                switch (cell.getCellType()) {
                    case STRING -> System.out.print(cell.getStringCellValue());
                    case NUMERIC, FORMULA -> System.out.print(cell.getNumericCellValue());
                    case BOOLEAN -> System.out.print(cell.getBooleanCellValue());
                }
                System.out.print("|");
            }
            System.out.println();
        }

        fileInputStream.close();
    }
}

在这里插入图片描述
在这里插入图片描述

测试结果

在这里插入图片描述

Excel 工作表中写入公式单元格

package com.apache.poi.demo;

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;

/**
 * Excel 工作表中写入公式单元格
 */
public class WriteDataFromFormulaCell {
    public static void main(String[] args) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        String sheetName = "Number";
        XSSFSheet sheet = workbook.createSheet(sheetName);
        XSSFRow row = sheet.createRow(0);

        row.createCell(0).setCellValue(10);
        row.createCell(1).setCellValue(20);
        row.createCell(2).setCellValue(30);

        /**
         * setCellFormula设置单元格公式,A1*B1*C1,单元格列名,
         * A1*B1*C1相当于单元格的值等于第一行第一个单元格乘以第一行第二个单元格乘以第一行第三个单元格
         */
        row.createCell(3).setCellFormula("A1*B1*C1");

        String filePath = ".\\datafiles\\calc.xlsx";
        // new FileOutputStream(filePath, true);true表示文件不存在,自动生成
        FileOutputStream fileOutputStream = new FileOutputStream(filePath, true);
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        workbook.close();
    }
}

生成文件
在这里插入图片描述
文件内容
在这里插入图片描述

从受密码保护的Excel中读取数据

一个excel文件,被密码进行保护,如何读取里面的数据。表格数据如下
在这里插入图片描述

方式一

package com.apache.poi.demo;

import org.apache.poi.ss.usermodel.WorkbookFactory;
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.FileInputStream;
import java.io.IOException;

/**
 * 从受密码保护的Excel中读取数据
 */
public class ReadingPasswordProtectedExcel {
    public static void main(String[] args) throws IOException {

        String path = ".\\datafiles\\customers.xlsx";
        FileInputStream fis = new FileInputStream(path);
        // 密码
        String password = "test123";

        // 根据可能受密码保护的给定InputStream创建适当的HSSFWorkbook/XSSFWorkbook。
        XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(fis, password);
        // 获取指定的工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 一共有5行数据,索引从0开始
        int rows = sheet.getLastRowNum();
        // 一共有3列,索引从1开始
        int cols = sheet.getRow(0).getLastCellNum();

        // 使用for循环读取数据
        for (int r = 0; r <= rows; r++) {
            XSSFRow row = sheet.getRow(r);
            for (int c = 0; c < cols; c++) {
                XSSFCell cell = row.getCell(c);
                switch (cell.getCellType()) {
                    case NUMERIC, FORMULA -> System.out.print(cell.getNumericCellValue());
                    case STRING -> System.out.print(cell.getStringCellValue());
                    case BOOLEAN -> System.out.print(cell.getBooleanCellValue());
                }
                System.out.print(" | ");
            }
            System.out.println();
        }

        // 关闭流
        workbook.close();
        fis.close();
    }
}

测试结果

在这里插入图片描述

方式二

package com.apache.poi.demo;

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

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * 从受密码保护的Excel中读取数据
 */
public class ReadingPasswordProtectedExcel2 {
    public static void main(String[] args) throws IOException {
        String path = ".\\datafiles\\customers.xlsx";
        FileInputStream fis = new FileInputStream(path);
        // 密码
        String password = "test123";

        // 根据可能受密码保护的给定InputStream创建适当的HSSFWorkbook/XSSFWorkbook。
        XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(fis, password);
        // 获取指定的工作表
        XSSFSheet sheet = workbook.getSheetAt(0);

        // 使用迭代器来读取表格中的数据
        Iterator<Row> rowIterator = sheet.rowIterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                    case NUMERIC, FORMULA -> System.out.print(cell.getNumericCellValue());
                    case STRING -> System.out.print(cell.getStringCellValue());
                    case BOOLEAN -> System.out.print(cell.getBooleanCellValue());
                }
                System.out.print(" | ");
            }
            System.out.println();
        }
        // 关闭流
        workbook.close();
        fis.close();
    }
}

测试结果

在这里插入图片描述

填充背景色和前景色到单元格中

package com.apache.poi.demo;

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;

public class FormattingCellColor {
    public static void main(String[] args) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");
        XSSFRow row = sheet.createRow(1);

        // 设置背景色
        XSSFCellStyle style = workbook.createCellStyle();
        style.setFillBackgroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
        style.setFillPattern(FillPatternType.BIG_SPOTS);

        // 创建第一个单元格
        XSSFCell cell = row.createCell(1);
        cell.setCellValue("welcome");
        cell.setCellStyle(style);

        //设置前景色
        style = workbook.createCellStyle();
        style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.BIG_SPOTS);

        // 创建第二个单元格
        cell = row.createCell(2);
        cell.setCellValue("Automation");
        cell.setCellStyle(style);

        String path = ".\\datafiles\\style.xlsx";
        FileOutputStream fos = new FileOutputStream(path, true);
        workbook.write(fos);
        workbook.close();
        fos.close();

        System.out.println("Done!!!");
    }
}

测试结果

在这里插入图片描述
生成的表格样式
在这里插入图片描述

将HashMap格式写入表格

package com.apache.poi.demo;

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.HashMap;
import java.util.Map;

/**
 *
 */
public class HashMapExcel {
    public static void main(String[] args) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Student data");

        Map<String, String> data = new HashMap<>();
        data.put("101", "John");
        data.put("102", "Smith");
        data.put("103", "Scott");
        data.put("104", "Kim");
        data.put("105", "Mary");

        int rowNo = 0;
        for (Map.Entry entry : data.entrySet()) {
            XSSFRow row = sheet.createRow(rowNo++);
            row.createCell(0).setCellValue((String) entry.getKey());
            row.createCell(1).setCellValue((String) entry.getValue());
        }
        FileOutputStream fos = new FileOutputStream(".\\datafiles\\student.xlsx", true);
        workbook.write(fos);
        workbook.close();
        fos.close();

        System.out.println("Excel Written Successfully!");
    }
}

测试结果

在这里插入图片描述
控制台输出
在这里插入图片描述

从excel中读取数据到HashMap中

package com.apache.poi.demo;

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

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 把表格数据读取到HashMap中
 */
public class ExcelToHashMap {
    public static void main(String[] args) throws IOException {
        String path = ".\\datafiles\\student.xlsx";
        FileInputStream fis = new FileInputStream(path);

        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheet("Student data");

        int rows = sheet.getLastRowNum();
        HashMap<String, String> data = new HashMap<>();

        // 读取数据从表格到HashMap
        for (int r = 0; r <= rows; r++) {
            String key = sheet.getRow(r).getCell(0).getStringCellValue();
            String value = sheet.getRow(r).getCell(1).getStringCellValue();
            data.put(key, value);
        }

        // 读取数据从HashMap中
        for (Map.Entry entry : data.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
        System.out.println(data);
        workbook.close();
        fis.close();
    }
}

测试结果

在这里插入图片描述

从数据库中读取数据并写入Excel

springboot的maven项目添加postgresql数据库依赖

 <!--postgresql依赖-->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
package com.apache.poi.demo;

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.sql.*;

/**
 * 从数据库中读取数据并写入Excel
 */
public class DataBaseToExcel {

    /**
     * url
     */
    private static final String url = "jdbc:postgresql://localhost:5432/cps";

    /**
     * 用户名
     */
    private static final String username = "postgres";

    /**
     * 密码
     */
    private static final String password = "admin";

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

        // 连接到数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        // statement/query
        Statement statement = connection.createStatement();
        String sql = "select * from departments";
        ResultSet rs = statement.executeQuery(sql);

        // 表格
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Locations Data");

        // 创建表格标题行

        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("department_id");
        row.createCell(1).setCellValue("department_name");
        row.createCell(2).setCellValue("manager_id");
        row.createCell(3).setCellValue("location_id");
        int rowNum = 1;
        while (rs.next()) {

            String departmentId = rs.getString("department_id");
            String departmentName = rs.getString("department_name");
            String managerId = rs.getString("manager_id");
            String locationId = rs.getString("location_id");

            row = sheet.createRow(rowNum++);

            row.createCell(0).setCellValue(departmentId);
            row.createCell(1).setCellValue(departmentName);
            row.createCell(2).setCellValue(managerId);
            row.createCell(3).setCellValue(locationId);
        }

        FileOutputStream fos = new FileOutputStream(".\\datafiles\\department.xlsx");
        workbook.write(fos);
        workbook.close();
        fos.close();
         //关闭数据库连接
        connection.close();
    }
}

测试结果

在这里插入图片描述

从Excel中读取数据并写入数据库表

excel内容

在这里插入图片描述

package com.apache.poi.demo;

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

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;

/**
 * 从Excel中读取数据并写入数据库表
 */
public class ExcelToDatabase {

    /**
     * url
     */
    private static final String url = "jdbc:postgresql://localhost:5432/cps";

    /**
     *
     */
    private static final String username = "postgres";

    /**
     * 密码
     */
    private static final String password = "admin";

    public static void main(String[] args) throws SQLException, IOException {
        // 连接到数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        // statement/query
        Statement statement = connection.createStatement();
        String sql = "create table test.departments (department_id int4 not null,department_name varchar(30) not null,manager_id int4 null,location_id int4 null)";
        statement.execute(sql);

        // 表格
        FileInputStream fis = new FileInputStream(".\\datafiles\\department.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheet("Locations Data");

        int rows = sheet.getLastRowNum();


        for (int r = 1; r <= rows; r++) {
            XSSFRow row = sheet.getRow(r);
            double departmentId = Double.parseDouble(row.getCell(0).getStringCellValue());
            String departmentName = row.getCell(1).getStringCellValue();
            int managerId = Integer.parseInt(row.getCell(2).getStringCellValue());
            int locationId = Integer.parseInt(row.getCell(3).getStringCellValue());

            sql = "insert into test.departments values(?,?,?,?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setDouble(1, departmentId);
            preparedStatement.setString(2, departmentName);
            preparedStatement.setInt(3, managerId);
            preparedStatement.setInt(4, locationId);
            preparedStatement.executeUpdate();

            // 提交sql
            statement.execute("commit");
        }
        workbook.close();
        fis.close();
        connection.close();

    }
}

生成的数据表

在这里插入图片描述

Selenium中的数据驱动测试

maven依赖

<!--selenium的java依赖-->
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.20.0</version>
        </dependency>
         <!--TestNg的依赖-->
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.10.1</version>
            <scope>test</scope>
        </dependency>

获取提交按钮的Xpath

在这里插入图片描述

自动化登录的地址:https://admin-demo.nopcommerce.com/login

工具类

package com.apache.poi.demo;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class XLUtility {

    public FileInputStream fis;
    public FileOutputStream fos;
    public XSSFWorkbook workbook;
    public XSSFSheet sheet;
    public XSSFRow row;
    public XSSFCell cell;
    public CellStyle style;
    String path = null;

    XLUtility(String path) {
        this.path = path;
    }

    /**
     * 获取工作表中的行数
     *
     * @param sheetName 工作表名
     * @return 表格行数
     * @throws IOException 抛出IO异常
     */
    public int getRowCount(String sheetName) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        workbook.close();
        fis.close();
        return rowCount;
    }

    /**
     * 获取工作表中行所在的单元格数量
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @return 行所在的单元格数量
     * @throws IOException 抛出IO异常
     */
    public int getCellCount(String sheetName, int rowNum) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        int cellCount = row.getLastCellNum();
        workbook.close();
        fis.close();
        return cellCount;
    }

    /**
     * 获取单元格内容
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @param cellNum   单元格号
     * @return 单元格内容
     * @throws IOException 抛出IO异常
     */
    public String getCellData(String sheetName, int rowNum, int cellNum) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        cell = row.getCell(cellNum);

        DataFormatter formatter = new DataFormatter();
        String data;
        try {
            data = formatter.formatCellValue(cell);
        } catch (Exception e) {
            data = "";
        }
        workbook.close();
        fis.close();
        return data;
    }

    /**
     * 设置表格单元格内容
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @param cellNum   单元格号
     * @param data      单元格内容
     * @throws IOException 抛出IO异常
     */
    public void setCellData(String sheetName, int rowNum, int cellNum, String data) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        cell = row.getCell(cellNum);
        cell.setCellValue(data);

        fos = new FileOutputStream(path);
        workbook.write(fos);
        workbook.close();
        fis.close();
        fos.close();
    }

    /**
     * 单元格填充颜色
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @param cellNum   单元格号
     * @throws IOException 抛出IO异常
     */
    public void fillGreenColor(String sheetName, int rowNum, int cellNum) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        cell = row.getCell(cellNum);
        style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cell.setCellStyle(style);
        workbook.write(fos);
        workbook.close();
        fis.close();
        fos.close();
    }
}

案例代码

package com.apache.poi.demo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class DataDriverTest {

    WebDriver driver;

    @BeforeClass
    public void setup() {
        // 将chromedriver下载放到自己的一个目录中,并在代码中设置
        System.setProperty("webdriver.chrome.driver", "..\\selenium-java-demo\\driver\\chromedriver.exe");

        //使用驱动实例并开启对话
        driver = new ChromeDriver();

        // 建立等待策略
        driver.manage().timeouts().implicitlyWait(500000, TimeUnit.SECONDS);

        // 窗口最大化
        driver.manage().window().maximize();
    }


    @Test(dataProvider = "LoginData")
    public void loginTest(String user, String pwd, String exp) {
        String url = "https://admin-demo.nopcommerce.com/login";
        // 打开的url
        driver.get(url);
        WebElement txtEmail = driver.findElement(By.id("Email"));
        // 清空元素的输入
        txtEmail.clear();
        // 输入内容
        txtEmail.sendKeys(user);

        WebElement txtPassword = driver.findElement(By.id("Password"));
        txtPassword.clear();
        txtPassword.sendKeys(pwd);

        // LOG IN按钮的Xpath陆路径
        String xPath = "/html/body/div[6]/div/div/div/div/div[2]/div[1]/div/form/div[3]/button";
        //  点击LOG IN按钮
        driver.findElement(By.xpath(xPath)).click();

        String expTitle = "Dashboard / nopCommerce administration";
        String actTitle = driver.getTitle();

        if (exp.equals("Valid")) {
            if (expTitle.equals(actTitle)) {
                driver.findElement(By.linkText("Logout")).click();
                Assert.assertTrue(true);
            } else {
                Assert.assertTrue(false);
            }
        } else if (exp.equals("Invalid")) {
            if (expTitle.equals(actTitle)) {
                driver.findElement(By.linkText("Logout")).click();
                Assert.assertTrue(false);
            } else {
                Assert.assertTrue(true);
            }
        }


    }

    /**
     * 数据提供者
     * 必须返回Object[][]数组类型
     */
    @DataProvider(name = "LoginData")
    public String[][] getData() throws IOException {
        // 从excel中获取数据
        String path = ".\\datafiles\\loginData.xlsx";
        XLUtility util = new XLUtility(path);
        int totalRows = util.getRowCount("Sheet1");
        int totalCols = util.getCellCount("Sheet1", 1);
        String loginData[][] = new String[totalRows][totalCols];
        for (int i = 1; i < totalRows; i++) {
            for (int j = 0; j < totalCols; j++) {
                String cellData = util.getCellData("Sheet1", i, j);
                loginData[i-1][j] = cellData;
            }
        }
        return loginData;
    }

    @AfterClass
    void tearDown() {
        driver.quit();
    }
}

在Selenium中将WebTable数据写入Excel表(网页数据抽取)

package com.apache.poi.demo;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
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.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class XLUtility {

    public FileInputStream fis;
    public FileOutputStream fos;
    public XSSFWorkbook workbook;
    public XSSFSheet sheet;
    public XSSFRow row;
    public XSSFCell cell;
    public CellStyle style;
    String path = null;

    XLUtility(String path) {
        this.path = path;
    }

    /**
     * 获取工作表中的行数
     *
     * @param sheetName 工作表名
     * @return 表格行数
     * @throws IOException 抛出IO异常
     */
    public int getRowCount(String sheetName) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        workbook.close();
        fis.close();
        return rowCount;
    }

    /**
     * 获取工作表中行所在的单元格数量
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @return 行所在的单元格数量
     * @throws IOException 抛出IO异常
     */
    public int getCellCount(String sheetName, int rowNum) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        int cellCount = row.getLastCellNum();
        workbook.close();
        fis.close();
        return cellCount;
    }

    /**
     * 获取单元格内容
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @param cellNum   单元格号
     * @return 单元格内容
     * @throws IOException 抛出IO异常
     */
    public String getCellData(String sheetName, int rowNum, int cellNum) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        cell = row.getCell(cellNum);

        DataFormatter formatter = new DataFormatter();
        String data;
        try {
            data = formatter.formatCellValue(cell);
        } catch (Exception e) {
            data = "";
        }
        workbook.close();
        fis.close();
        return data;
    }

    /**
     * 设置表格单元格内容
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @param cellNum   单元格号
     * @param data      单元格内容
     * @throws IOException 抛出IO异常
     */
    public void setCellData(String sheetName, int rowNum, int cellNum, String data) throws IOException {
        File xlFile = new File(path);
        if (!xlFile.exists()) {
            // 如果文件不存在就创建一个新文件
            workbook = new XSSFWorkbook();
            fos = new FileOutputStream(path);
            workbook.write(fos);
        }
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        if (workbook.getSheetIndex(sheetName) == -1) {
            // 工作表不存在就创建
            workbook.createSheet(sheetName);
        }
        sheet = workbook.getSheet(sheetName);
        if (sheet.getRow(rowNum) == null) {
            // 表格行不存在就创建
            row = sheet.createRow(rowNum);
        }
        row = sheet.getRow(rowNum);
        cell = row.createCell(cellNum);
        cell.setCellValue(data);

        fos = new FileOutputStream(path);
        workbook.write(fos);
        workbook.close();
        fis.close();
        fos.close();
    }

    /**
     * 单元格填充颜色
     *
     * @param sheetName 工作表名
     * @param rowNum    表格行号
     * @param cellNum   单元格号
     * @throws IOException 抛出IO异常
     */
    public void fillGreenColor(String sheetName, int rowNum, int cellNum) throws IOException {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(rowNum);
        cell = row.getCell(cellNum);
        style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cell.setCellStyle(style);
        workbook.write(fos);
        workbook.close();
        fis.close();
        fos.close();
    }
}

package com.apache.poi.demo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 在Selenium中将WebTable数据写入Excel表(网页数据抽取)
 */
public class WebTableToExcel {
    public static void main(String[] args) throws IOException {
        //设置环境变量
        String driverPath = ".\\selenium-java-demo\\driver\\chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", driverPath);

        // 使用驱动实例开启会话
        WebDriver driver = new ChromeDriver();
        //等待策略
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        // 窗口最大化
        driver.manage().window().maximize();

        //导航到的url
        String url = "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population";
        driver.get(url);

        String path = ".\\datafiles\\population.xlsx";
        XLUtility utility = new XLUtility(path);

        // 设置标题行
        utility.setCellData("Sheet1", 0, 0, "Location");
        utility.setCellData("Sheet1", 0, 1, "Population");
        utility.setCellData("Sheet1", 0, 2, "% of world");
        utility.setCellData("Sheet1", 0, 3, "Date");
        utility.setCellData("Sheet1", 0, 4, "Source");

        // 捕获表格数据
        WebElement table = driver.findElement(By.xpath("//*[@id=\"mw-content-text\"]/div[1]/table/tbody"));
        // 在网页中表格的行
        int size = table.findElements(By.xpath("tr")).size();

        for (int r = 1; r <= size; r++) {
            String location = table.findElement(By.xpath("tr[" + r + "]/td[1]")).getText();
            String population = table.findElement(By.xpath("tr[" + r + "]/td[2]")).getText();
            String world = table.findElement(By.xpath("tr[" + r + "]/td[3]")).getText();
            String date = table.findElement(By.xpath("tr[" + r + "]/td[4]")).getText();
            String source = table.findElement(By.xpath("tr[" + r + "]/td[5]")).getText();
            System.out.println(location + " " + population + " " + world + " " + date + " " + source);

            utility.setCellData("Sheet1", r, 0, location);
            utility.setCellData("Sheet1", r, 1, population);
            utility.setCellData("Sheet1", r, 2, world);
            utility.setCellData("Sheet1", r, 3, date);
            utility.setCellData("Sheet1", r, 4, source);
        }
        System.out.println("Web scraping is done successfully...");
        driver.close();
    }
}

测试结果

生成population.xlsx
在这里插入图片描述

在Excel中单元格内容为日期格式

package com.apache.poi.demo;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.XSSFCell;
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.Date;

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

        // 创建一个空的工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();

        // 创建一个工作表格
        XSSFSheet sheet = workbook.createSheet("Date formats");
        sheet.setColumnWidth(0, 256 * 20);

        XSSFCell cell = sheet.createRow(0).createCell(0);

        cell.setCellValue(new Date());


        CreationHelper creationHelper = workbook.getCreationHelper();

        // 格式化  yyyy-MM-dd HH:mm:ss
        CellStyle style = workbook.createCellStyle();
        style.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
        cell.setCellStyle(style);


        FileOutputStream fos = new FileOutputStream(".\\datafiles\\dataformats.xlsx", true);

        workbook.write(fos);

        fos.close();
        workbook.close();
    }
}

测试结果

在这里插入图片描述

代码地址

https://gitee.com/BAIXUEQIAN/java-study/tree/develop/Apache-Poi-Demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/605676.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Apple 发布新款 iPad Pro 和 iPad Air:性能和设计的巨大飞跃

Apple 发布新款 iPad Pro 和 iPad Air&#xff1a;性能和设计的巨大飞跃 概述 苹果公司最近的“Let Loose”活动在科技界掀起了轩然大波&#xff0c;推出了最新的 iPad Pro 和 iPad Air 型号&#xff0c;在性能、设计和功能方面取得了前所未有的改进。在本文中&#xff0c;我…

【XR806开发板试用】使用FDCM操作Flash记录开机次数

一、寻找系统分配的自定义用户数据地址 &#xff08;1&#xff09;XR806的Flash布局 如图1所示&#xff0c;FLASH的布局有两种&#xff1a; 1、没有开启OTA模式&#xff1b;Image1PaddingSysinfo 2、开启OTA模式&#xff1b;Image1PaddingSysinfoOTA area Image2 Padding 如图…

智算中心“火”了?引领算力发展新潮流

去年大模型的空前发展&#xff0c;人工智能也终于迎来了属于自己的“文艺复兴”&#xff0c;众多的模型相继发布&#xff0c;继而催生了整个行业对于智能算力需求的激增。 市场需求与技术驱动仿佛现实世界的左右脚&#xff0c;催动着世界文明的齿轮向前滚动。在全球经济角逐日…

django中的cookie与session

获取cookie request.COOKIE.GET 使用cookie response.set-cookie views.py from django.http import HttpResponse from django.shortcuts import render# Create your views here. def cookie_test(request):r HttpResponse("hello world")r.set_cookie(lan, py…

AQ6360 横河 光谱分析仪精华帖,收藏保存

AQ6360是一款由日本横河&#xff08;YOKOGAWA&#xff09;生产的光谱分析仪&#xff0c;其主要技术参数包括波长范围、波长精度和波长线性度等。AQ6360的波长范围为1200~1650nm &#xff0c;具有较高的波长精度&#xff0c;在1520~1580nm范围内为0.02nm&#xff0c;在1580~1620…

Colab/PyTorch - 001 PyTorch Basics

Colab/PyTorch - 001 PyTorch Basics 1. 源由2. PyTorch库概览3. 处理过程2.1 数据加载与处理2.2 构建神经网络2.3 模型推断2.4 兼容性 3. 张量介绍3.1 构建张量3.2 访问张量元素3.3 张量元素类型3.4 张量转换&#xff08;NumPy Array&#xff09;3.5 张量运算3.6 CPU v/s GPU …

从0开始学习python(六)

目录 前言 1、循环结构 1.1 遍历循环结构for 1.2 无限循环结构while 总结 前言 上一篇文章我们讲到了python的顺序结构和分支结构。这一章继续往下讲。 1、循环结构 在python中&#xff0c;循环结构分为两类&#xff0c;一类是遍历循环结构for&#xff0c;一类是无限循环结…

【工具推荐定制开发】一款轻量的批量web请求命令行工具支持全平台:hey,基本安装、配置、使用

背景 在开发 Web 应用的过程中&#xff0c;作为开发人员&#xff0c;为了确认接口的性能能够达到要求&#xff0c;我们往往需要一个接口压测工具&#xff0c;帮助我们快速地对我们所提供的 Web 服务发起批量请求。在接口联调的过程中&#xff0c;我们通常会用 Postman 等图形化…

气死!又被数据骗了!

做数据分析的人做的久了&#xff0c;就会自然而然产生一种想法&#xff0c;认为数据展示出来的东西一定是正确的。毕竟如果连我们自己都质疑数据分析的权威性和说服力&#xff0c;那我们数据分析人的工作不就成了白费功夫了嘛。 一开始&#xff0c;我也认为这是一条不可撼动的…

JVM认识之垃圾收集算法

一、标记-清除算法 1、定义 标记-清除算法是最基础的垃圾收集算法。它分为标记和清除两个阶段。先标记出所有需要回收的对象&#xff08;即垃圾&#xff09;&#xff0c;在标记完成后再统一回收所有垃圾对象。 2、优点和缺点 优点&#xff1a;实现简单缺点&#xff1a; 可能…

C++类和对象详解(一)

目录 面向过程和面向对象初步认识类的引入类的定义类的两种定义方式声明和定义全部放在类体中 声名定义分离 类的作用域成员变量命名规则建议访问限定符 类的封装类的实例化类对象模型类的对象大小的计算扩展 结构体内存对齐规则 感谢各位大佬对我的支持,如果我的文章对你有用,…

Linux系统一步一脚印式学习

Linux操作系统具有许多特点和优势。首先&#xff0c;它是开放源代码的&#xff0c;也就意味着任何人都可以对源代码进行查看和修改。其次&#xff0c;可以同时支持多个用户且可以同时执行多个任务&#xff0c;此外&#xff0c;Linux操作系统也非常稳定和安全。相对于其他操作系…

MyBatis认识

一、定义 MyBatis是一款优秀的持久层框架&#xff0c;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO&#xff08;Plain Old Java O…

关于zabbix简介及zabbix服务端的部署

文章目录 一、zabbix概念1、zabbix简介2、zabbix主要特点3、zabbix运行机制4、zabbix应用场景5、zabbix监控原理6、zabbix的子程序7、zabbix监控的架构模式7.1 server-client架构7.2 server-proxy-client架构7.3 master-node-client 二、部署zabbix1、服务器配置2、服务器环境3…

ruoyi-nbcio 基于flowable规则的多重并发网关的任意跳转

更多ruoyi-nbcio功能请看演示系统 gitee源代码地址 前后端代码&#xff1a; https://gitee.com/nbacheng/ruoyi-nbcio 演示地址&#xff1a;RuoYi-Nbcio后台管理系统 http://218.75.87.38:9666/ 更多nbcio-boot功能请看演示系统 gitee源代码地址 后端代码&#xff1a; h…

认识下MapReduce

&#x1f50d; 什么是MapReduce&#xff1f; MapReduce是一种分布式计算模型&#xff0c;最初由Google提出&#xff0c;用于处理大规模数据集的并行计算。它将数据处理任务分解成独立的Map和Reduce两个阶段&#xff0c;以实现分布式计算和并行化处理。Map阶段负责将输入数据映…

自然语言处理(NLP)技术有哪些运用?

目录 一、自然语言处理&#xff08;NLP&#xff09;技术有哪些运用&#xff1f; 二、Python进行文本的情感分析 1、NLTK库: 2、TextBlob库: 三、错误排除 一、自然语言处理&#xff08;NLP&#xff09;技术有哪些运用&#xff1f; 自然语言处理&#xff08;NLP&#xff09…

DAY 3

1. #include "widget.h"Widget::Widget(QWidget *parent): QWidget(parent) {this->resize(540,415);this->setFixedSize(540,415);//窗口标题this->setWindowTitle("盗版QQ");//窗口图标this->setWindowIcon(QIcon("E:\\qq\\pictrue\\pi…

520情人节送什么礼物?五款好物分享,情侣必看!

在浪漫的520情人节&#xff0c;为心爱的人挑选一份特别的礼物是每对情侣表达爱意的重要方式。市场上琳琅满目的选择让人眼花缭乱&#xff0c;究竟什么样的礼物能触动TA的心弦&#xff1f;本篇分享将为您精选五款既实用又充满情意的好物&#xff0c;无论是甜蜜的开始还是长久的陪…

linux上go项目打包与部署

1.第一步把项目打包 1.确保本地goland的操作系统为linux go env找到GOOS如果为window就修改为Linux 修改命令为 go env -w GOOSlinux2.打包 在项目根目录下输入 go build main.go然后项目根目录下会出现一个mian的二进制文件 3.上传包 将 main 程序包放到服务的目录下&…
最新文章