获取Excel数据(或部分数据)并导出成txt文本格式

本文介绍如何使用Java和jxl库从Excel文件中读取特定数据,并将其写入到TXT文件中。示例代码展示了如何遍历指定列的数据,并进行格式化输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运行代码前先导入jxl架包,以下代码仅供参考:

测试excel文件(我要获取该excel的内容为省、县、乡、村、组和PH的值):

 

 

ExcelTest01类代码如下:

// 读取Excel的类
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class ExcelTest01 {
	public static void main(String args[]) {
		try {
			System.out.println("begini");
			Workbook book = Workbook.getWorkbook(new File("a.xls"));
			// 获得第一个工作表对象
			Sheet sheet = book.getSheet(0);
			// 得到第一列第一行的单元格

			try {
				File file = new File("c:/IAI.txt");
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();
				BufferedWriter output = new BufferedWriter(new FileWriter(file));

				for (int i = 2; i < 4896; i++) {
					Cell cell1 = sheet.getCell(23, i);// PH

					Cell cell2 = sheet.getCell(4, i);// 省
					Cell cell3 = sheet.getCell(7, i);// 县
					Cell cell4 = sheet.getCell(8, i);// 乡
					Cell cell5 = sheet.getCell(9, i);// 村
					Cell cell6 = sheet.getCell(10, i);// 组

					String ph = cell1.getContents();

					String sheng = cell2.getContents();
					String xian = cell3.getContents();
					String xiang = cell4.getContents();
					String cun = cell5.getContents();
					String zu = cell6.getContents();

					System.out.println("第" + (i + 1) + "行" + sheng + xian + xiang
							+ cun + zu+"\t"+ph);
					output.write("第" + (i + 1) + "行" + sheng + xian + xiang
							+ cun + zu+"\t"+ph+"\n");
					output.newLine();
				}
				output.close();
			} catch (Exception ex) {
				System.out.println(ex);
			}
			book.close();
			System.out.println("end");
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

  

运行结果如下图所示:

 

生成txt文本内容如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值