Linux下java读取xls格式的excel内容并写入txt
时间: 2024-02-20 19:59:08 浏览: 115
在Linux下使用Java读取xls格式的Excel并将内容写入txt可以使用Apache POI库来实现。下面是实现的步骤:
1. 引入依赖库:在pom.xml文件中添加以下依赖:
```xml
<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>
```
2. 读取Excel文件:使用HSSFWorkbook类来读取xls格式的Excel文件,代码如下:
```java
File file = new File("file.xls");
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
```
3. 遍历Excel表格:使用HSSFRow和HSSFCell类来遍历Excel表格,代码如下:
```java
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
if (cell != null) {
sb.append(cell.toString() + ",");
}
}
// 将每一行数据写入txt文件
FileWriter fw = new FileWriter("output.txt", true);
fw.write(sb.toString() + "\n");
fw.close();
}
```
4. 完整代码如下:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
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;
public class ReadExcel {
public static void main(String[] args) throws IOException {
File file = new File("file.xls");
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
if (cell != null) {
sb.append(cell.toString() + ",");
}
}
FileWriter fw = new FileWriter("output.txt", true);
fw.write(sb.toString() + "\n");
fw.close();
}
workbook.close();
}
}
```
注意:需要在当前目录下放置file.xls文件,程序会生成output.txt文件并将Excel中的数据写入其中。
阅读全文
相关推荐















