Java 打开Excel,往Excel中存入值,保存的excel格式分别是xls和xlsx

https://mirrors.cnnic.cn/apache/poi/xmlbeans/release/src/

 

 

package Excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class WriteExcel {

    Date dt = new Date();
    SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmss");
    String time = format.format(dt);

    public void WriteExcelxls() {

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(new File(".\\Log\\旧的EXCEL文件_"+time+".xls"));
            HSSFWorkbook workxls = new HSSFWorkbook();
            HSSFSheet sheet = workxls.createSheet(time);
            HSSFRow row = workxls.getSheet(time).createRow(0);


            for (short i = 0; i < 10; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue("测试" + i);
            }

            sheet.createRow(1).createCell(1).setCellValue("1234567890");
            sheet.createRow(2).createCell(0).setCellValue(Calendar.getInstance());
            sheet.createRow(3).createCell(0).setCellValue("字符串");
            sheet.createRow(4).createCell(0).setCellValue(true);
            sheet.createRow(5).createCell(0).setCellType(CellType.ERROR);
            workxls.write(out);
            out.close();
            System.out.println("旧的EXCEL文件_.xls written successfully on disk.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void WriteExcelxlsx() {

        File file = new File(".\\Log\\新的EXCEL文件_"+time+".xlsx");
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFRow row = workbook.createSheet(time).createRow(0);
            XSSFSheet sheet = workbook.getSheet(time);

            for (short i = 0; i < 10; i++) {
                XSSFCell cell = row.createCell(i);
                cell.setCellValue("新的EXCEL文件" + i);
            }

            sheet.createRow(1).createCell(1).setCellValue("1234567890");
            sheet.createRow(2).createCell(0).setCellValue(Calendar.getInstance());
            sheet.createRow(3).createCell(0).setCellValue("字符串");
            sheet.createRow(4).createCell(0).setCellValue(true);
            sheet.createRow(5).createCell(0).setCellType(CellType.ERROR);
            workbook.write(out);
            out.close();
            System.out.println("新的EXCEL文件_.xlsx written successfully on disk.");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

  

package Excel;

import org.testng.annotations.Test;

public class TestExcel {

    @Test(priority = 1)
    private void Testold()
    {
        WriteExcel aaa = new WriteExcel();
        aaa.WriteExcelxls();

    }

    @Test(priority = 2)
    public void Testnew()
    {
        WriteExcel aaa = new WriteExcel();
        aaa.WriteExcelxlsx();

    }
}

  依赖:

<?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>

    <groupId>Jasmine</groupId>
    <artifactId>Test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.13.1</version>
        </dependency>
    </dependencies>
</project>

  

 

package Excel;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class WriteExcelMore {

    static Date dt = new Date();
    static SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmss");
    static String time = format.format(dt);


    public static void main(String args[]) {

        File file = new File(".\\Log\\新的EXCEL文件_" + time + ".xls");
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            HSSFWorkbook workbook = new HSSFWorkbook(); //创建一个新的excel
            HSSFSheet sheet = workbook.createSheet(time);  //创建sheet页
            HSSFHeader header = sheet.getHeader();//创建header页
            header.setCenter("Title");

            HSSFRow[] row = new HSSFRow[3];
            row[0] = sheet.createRow(0);
            HSSFCell headerCell = row[0].createCell(5);
            headerCell.setCellValue(new HSSFRichTextString("标题"));
            //HSSFRow  row = workbook.getSheet(time).createRow(3);
            row[1] = sheet.createRow(1);

            for (short i = 0; i < 5; i++) {
                HSSFCell cell = row[1].createCell(i);
                cell.setCellValue("新的EXCEL文件" + i);
            }


            row[2] = sheet.createRow(2);
            String[] arr = new String[5];
            String[] arr2 = {"aa", "bb", "cc", "dd", "ee"};
            for (short i = 0; i < 5; i++) {
                HSSFCell cell = row[2].createCell(i);
                cell.setCellValue(arr2[i]);
            }

            sheet.createRow(5).createCell(1).setCellValue("1234567890");
            sheet.createRow(6).createCell(0).setCellValue(Calendar.getInstance());
            sheet.createRow(7).createCell(0).setCellValue("字符串");
            sheet.createRow(8).createCell(0).setCellValue(true);
            sheet.createRow(9).createCell(0).setCellType(CellType.ERROR);

            //设置footer
            sheet.setGridsPrinted(false);
            HSSFFooter footer = sheet.getFooter();
            footer.setRight("page " + HeaderFooter.page() + "of" + HeaderFooter.numPages());

            workbook.write(out);
            out.close();
            System.out.println(file + " written successfully on disk.");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  

遇到的错如下:

1. Exception in thread "main" java.lang.NoClassDefFoundError: 

org/dom4j/DocumentExceptionCaused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException

 

2. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/compress/archivers/zip/ZipFile

 

3. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap

 

4. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject

 

5. java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException

<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>3.0.0</version>
</dependency>

 

6. java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap


<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>

 


7. java.lang.NoClassDefFoundError: org/apache/commons/compress/archivers/zip/ZipFile

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>

 


8. java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;

 

上述都是包的问题,后来新建了一个项目,换成maven管理依赖包,一次性解决了。

 

 

update 20181122

将上述代码拖到UI自动化项目中,发现执行报各种错误,已添加到上面。 

都是jar包的问题,但是我已经将测试成功项目中的pom文件中的jar包都下载来了,却还是报各种错,解决了一个又遇到下一个。 (┬_┬)

maven打包,因为网络问题,有时候有的包未能下载下来,就自己下载jar包引用,可是(┬_┬)(┬_┬)无力

 

 

苦心人天不负,三千越界可吞吴。哈哈哈哈,在尝试了千万遍之后,终于成功了,下面是所有新引入的jar包,百度网盘链接如下:

其中红框框是为了解决excel中xlsx格式而引入的一系列jar包。

 

链接:https://pan.baidu.com/s/1JhKENJU1PLlgOwyrnptilg
提取码:ip2u
链接若失效,请联系我

转载于:https://www.cnblogs.com/qianjinyan/p/9758395.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Apache POI库来解析Excel文件。下面是一个使用Java解析Excel文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelParser { public static void main(String[] args) { String filePath = "path/to/your/excel/file.xlsx"; // 替换为你的Excel文件路径 try { FileInputStream fis = new FileInputStream(new File(filePath)); Workbook workbook; if (filePath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(fis); // 处理.xlsx文件 } else if (filePath.endsWith(".xls")) { workbook = new HSSFWorkbook(fis); // 处理.xls文件 } else { throw new IllegalArgumentException("The specified file is not Excel file"); } Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 for (Row row : sheet) { for (Cell cell : row) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { System.out.print(cell.getStringCellValue() + " "); } else if (cellType == CellType.NUMERIC) { System.out.print(cell.getNumericCellValue() + " "); } else if (cellType == CellType.BOOLEAN) { System.out.print(cell.getBooleanCellValue() + " "); } } System.out.println(); } workbook.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 请将代码的`"path/to/your/excel/file.xlsx"`替换为你实际的Excel文件路径。该代码会打开Excel文件并输出每个单元格的。你可以根据需要对解析的内容进行进一步处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值