1.先导包
2.直接上代码
package ExcelToTxt;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Demo01 {
// 从Excel表中读取数据,并输出到txt文件中
public static void main(String[] args) {
FileOutputStream out = null;
FileInputStream in = null;
try {
// 1.获取Excel输入流和Txt输出流
in = new FileInputStream("F:\\2021Java\\suanli\\cvrp.xlsx"); // Excel
out = new FileOutputStream("F:\\2021Java\\suanli\\cvrp.txt"); //txt
// 2.从输入流中读取Excel工作簿
XSSFWorkbook wb = new XSSFWorkbook(in);
// 3.从工作簿中获取工作表
Sheet sheet = wb.getSheet("Sheet1");
int num_row = sheet.getPhysicalNumberOfRows(); // 获取行数
// 4.读取Excel数据,并写入到TXT文件中
// 4.1 读取表头数据
String str = ""; // 用于存储每一行的字符串
int num_cel = sheet.getRow(0).getPhysicalNumberOfCells(); // 列数
for (int i = 0; i < num_cel; i++) { // 遍历标头的每一列
str = str + sheet.getRow(0).getCell(i).getStringCellValue() + "\t";
}
str += "\r";
out.write(str.getBytes(StandardCharsets.UTF_8));
// 4.2 读取表中数据
for (int i = 1; i < num_row; i++) { // 遍历行
str = "";
// 获取这一行的单元格个数
num_cel = sheet.getRow(i).getPhysicalNumberOfCells();
for (int j = 0; j < num_cel; j++) { // 遍历行的每一个单元格
str = str + (int) sheet.getRow(i).getCell(j).getNumericCellValue() + "\t";
}
str += "\r";
out.write(str.getBytes(StandardCharsets.UTF_8));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("执行完成!!!");
}
}
}