🌑

Hi Folks.

如何操作excel、word、pdf、md、txt、csv文件

Java 中操作各种文件类型(如 Excel、Word、PDF、Markdown、纯文本和 CSV)需要不同的库来实现。以下是一些基本的代码示例,分别针对不同格式进行读写或修改内容的操作:

操作 Excel (使用 Apache POI 库)

读取/写入 Excel (. Xls, .xlsx)

// 导入相关依赖
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

// 写入数据到Excel
try (Workbook workbook = new XSSFWorkbook(); // 新建一个XLSX工作簿
     FileOutputStream fileOut = new FileOutputStream("output.xlsx")) {
    
    Sheet sheet = workbook.createSheet("Sheet1"); // 创建新的sheet
    Row row = sheet.createRow(0); // 创建行
    Cell cell = row.createCell(0); // 创建单元格
    
    cell.setCellValue("Hello, Excel!"); // 设置单元格值

    workbook.write(fileOut); // 写入文件
} catch (IOException e) {
    e.printStackTrace();
}

// 读取数据从Excel
try ( FileInputStream file = new FileInputStream("input.xlsx");
      Workbook workbook = new XSSFWorkbook(file)) {

    Sheet sheet = workbook.getSheetAt(0);
    Row row = sheet.getRow(0);
    Cell cell = row.getCell(0);

    String value = cell.getStringCellValue(); // 获取单元格值

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

// 删除内容
// 需要找到特定单元格并清除其内容,例如:
row.getCell(0).setCellValue(null); // 清除单元格内容

操作 Word (. Doc, .docx) 使用 Apache POI 库中的 HWPF 或 XWPF

写入 Word (. docx)

// 导入相关依赖
import org.apache.poi.xwpf.usermodel.*;

// 写入内容到Word文档
try (XWPFDocument document = new XWPFDocument()) {
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    run.setText("Hello, Word!");
    
    FileOutputStream out = new FileOutputStream("output.docx");
    document.write(out);
} catch (IOException e) {
    e.printStackTrace();
}

// 删除内容需定位到具体的段落或运行,并移除它们
// 注意:删除操作通常比写入更为复杂,因为可能涉及到多个段落、图片等元素
// 下面是一个简单删除段落的例子:
List<XWPFParagraph> paragraphs = document.getParagraphs();
if (!paragraphs.isEmpty()) {
    paragraphs.remove(0); // 移除第一个段落
}

操作 PDF (使用 iText 或 Apache PDFBox 库)

写入 PDF

// 使用iText库
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

try {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
    document.open();
    document.add(new Paragraph("Hello, PDF!"));
    document.close();
} catch (Exception e) {
    e.printStackTrace();
}

// 删除内容较为复杂,通常涉及重新构造PDF文档结构,具体操作取决于库提供的API
// iText提供了一些更新PDF内容的方法,但通常是替换而不是删除特定内容。

// 使用PDFBox创建新页面或覆盖现有内容比较常见
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;

try (PDDocument doc = PDDocument.load(new File("input.pdf"))) {
    PDPage page = doc.getPage(0);
    PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
    // 要删除内容,通常不是直接删除而是覆盖原有内容
    // 实际上是重新绘制整个页面或者部分区域
    // 这里仅做关闭流处理,实际内容删除请查阅PDFBox官方文档
    contentStream.close();
    doc.save("output.pdf");
} catch (IOException e) {
    e.printStackTrace();
}

操作 Markdown (. md) 和纯文本 (. txt)

由于 Markdown 和纯文本都是基于文本格式,可以直接通过 Java 的 IO 流进行读写。

写入/读取文本文件

// 写入文本文件
try (PrintWriter writer = new PrintWriter(new FileWriter("output.md"))) {
    writer.println("# Hello, Markdown!");
    writer.flush();
} catch (IOException e) {
    e.printStackTrace();
}

// 读取文本文件
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 删除内容
// 对于文本文件,删除可以通过重写文件部分内容或整体覆盖实现
// 例如打开文件后,跳过不需要的部分再写入其他内容

操作 CSV (. csv)

写入/读取 CSV 文件

import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

// 写入CSV文件
try (FileWriter writer = new FileWriter("output.csv")) {
    writer.append("Name,Age\n");
    writer.append("John Doe,30\n");
    writer.flush();
} catch (IOException e) {
    e.printStackTrace();
}

// 读取CSV文件
try (BufferedReader reader = new BufferedReader(new FileReader("input.csv"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        String[] data = line.split(",");
        // 处理数据...
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 删除内容,CSV没有内置的“删除”概念,但可以通过重新写入文件时略过某些行来实现

请注意以上所有代码仅为简略示例,实际应用中应考虑异常处理、资源管理以及更复杂的文档结构操作。对于 Word、PDF 等格式,删除内容通常涉及查找、替换或重组文档结构。在使用任何第三方库前,请确保已经添加了对应的 Maven 或 Gradle 依赖项。

——Nov 18, 2023

Copyright © z1gui with Hexo.js at Earth.