首页 > 代码库 > 用java实现excel和txt文件互转

用java实现excel和txt文件互转



import java.io.*;
import jxl.*;
import jxl.write.*;

//用java将txt数据导入excel
public class CreateXLS
{
public static void main(String args[])
{
try
{
//打开文件
WritableWorkbook book= Workbook.createWorkbook(new File("测试.xls"));
//生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet=book.createSheet("第一页",0);
//在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
//以及单元格内容为test
Label label=new Label(0,0,"test");
//将定义好的单元格添加到工作表中
sheet.addCell(label);
/*生成一个保存数字的单元格
必须使用Number的完整包路径,否则有语法歧义
单元格位置是第二列,第一行,值为789.123*/
jxl.write.Number number = new jxl.write.Number(1,0,789.123);
sheet.addCell(number);
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e)
{
System.out.println(e);
}

}
}

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

//用java将excel数据导入txt

public class WriteTxt {

public static void main(String[] args) {
// TODO Auto-generated method stub
String filepath = "d:\\demo.xls";

try {
Workbook workbook = Workbook.getWorkbook(new File(filepath));
Sheet sheet = workbook.getSheet(0);
File file = new File("d:/1.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
// j为行数,getCell("列号","行号")
int j = sheet.getRows();
int y = sheet.getColumns();
for (int i = 0; i < j; i++) {
for(int x=0; x<y; x++){

Cell c = sheet.getCell(x, i);
String s = c.getContents();
bw.write(s);
bw.write(" ");
bw.flush();
}
bw.newLine();
bw.flush();
}
System.out.println("写入结束");
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}



遇到的问题:txt文件中单元格数据之间用|分割,用string.split("\\|");提取数据

用java实现excel和txt文件互转