600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java读取txt生成excel_读取TXT文件内容 生成Excel文件

java读取txt生成excel_读取TXT文件内容 生成Excel文件

时间:2023-03-25 15:54:10

相关推荐

java读取txt生成excel_读取TXT文件内容 生成Excel文件

需要用到jar文件:poi-3.0.1.jarpackage office;

/**

* 解析txt文件,输出到Excel文件

* @author JavaAlpha

* @date -7-28

* @version V 1.0

*/

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

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 WordReader {

/**

* @param args

*/

public static void main(String[] args) {

readFileByLine("E:/1.txt");

}

/**

* 以行为单位读取文件(文本文件)

*

* @param filePath

*/

public static void readFileByLine(String filePath) {

File file = new File(filePath);

BufferedReader bd = null;

Map str = new HashMap();

String s1 = "";

String s2 = "";

try {

bd = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gb2312"));// 编码转换(关键的地方)

String temp = "";

int line = 1;

while ((temp = bd.readLine()) != null) {

if (temp.length() > 0) {

s1 = temp.substring(0, 3);

s1 = s1.trim();

s2 = temp.substring(4);

s2 = s2.trim();

str.put(s1, s2);

}

++line;

}

createExcel(str);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (bd != null)

bd.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 输出Excel文件,输出格式为多行两列

* @param map

*/

static void createExcel(Map map) {

try {

// 新建一输出文件流

FileOutputStream fOut = new FileOutputStream("e:/2.xls");

File file = new File("e:/2.xls");

if (file.exists()) {

file.delete();

}

// 创建新的Excel 工作簿

HSSFWorkbook workbook = new HSSFWorkbook();

// 在Excel工作簿中建一工作表,其名为缺省值

// 如要新建一名为"联系人用户名和电话"的工作表,其语句为:

HSSFSheet sheet = workbook.createSheet("联系人用户名和电话");

HSSFRow row = null;

// 在索引0的位置创建单元格(左上端)

HSSFCell cell1 = null;

HSSFCell cell2 = null;

Iterator iter = map.entrySet().iterator();

int i = 0;

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry) iter.next();

Object key = entry.getKey();

Object val = entry.getValue();

row = sheet.createRow((short) i++);

cell1 = row.createCell((short) 0);

cell2 = row.createCell((short) 1);

// 定义单元格为字符串类型

cell1.setCellType(HSSFCell.CELL_TYPE_STRING);

cell2.setCellType(HSSFCell.CELL_TYPE_STRING);

// 在单元格中输入一些内容

cell1.setCellValue(key.toString());

cell2.setCellValue(val.toString());

if (i > 255) {

break;

}

}

// 把相应的Excel 工作簿存盘

workbook.write(fOut);

fOut.flush();

// 操作结束,关闭文件

fOut.close();

System.out.println("文件生成...");

} catch (Exception e) {

System.out.println("出现异常: " + e);

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。