程序运行前的txt文件格式如上图
程序运行后的excel文件如下图
package com.ultrapower.command;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
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;
public class Test {
static String inputfile="d:\\test001.txt";
static String outputexcel="d:\\test001.xls";
static String sheetname="测试";
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(new File(inputfile)));//获取流
XSSFWorkbook hwb = new XSSFWorkbook();// 新建一个Excel工作簿
XSSFSheet sheet = hwb.createSheet(sheetname);//新建一个工作表
//XSSFCellStyle cellStyle = hwb.createCellStyle();
XSSFRow row = null;//列
XSSFCell[] cell = null;//单元格数组
String str = null;
int i = 0;
//这里的str记录的是每一行的数据,由于源文件的数据都是用tab分隔的,所以要先切割,然后再添加到相对应的单元格里
while ((str = br.readLine()) != null) {
row = sheet.createRow(i);
//获取有几个分隔符
String[] s =str.split(" ");
int num =s.length;
cell = new XSSFCell[num];
for(int j=0;j<=(num-1);j++){
cell[j] = row.createCell(j);
cell[j].setCellValue(s[j]);
}
i++;
}
OutputStream out = new FileOutputStream(outputexcel);
System.out.println("转换完毕");
hwb.write(out);
out.close();
br.close();
}
}