当前位置:编程学习 > JAVA >>

java读取txt和excel赋值到二维数组的问题。

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class readtxt { public static void main(String[] args) { // TODO Auto-generated method stub List<String> list = new ArrayList<String>(); String filePath = "C:/a.xls"; InputStream fs = null; Workbook workBook = null; try { fs = new FileInputStream(filePath); workBook = Workbook.getWorkbook(fs); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } for (int n=0;n<3;n++){ Sheet sheet = workBook.getSheet(n); Cell cell = null; for (int j = 3; j < sheet.getRows(); j++) { StringBuffer sb = new StringBuffer(); for (int i = 3; i <6; i++) { cell = sheet.getCell(i, j); sb.append(cell.getContents()); sb.append("|"); } list.add(sb.toString()); } } workBook.close(); for(String ss:list){ System.out.println(ss); } } java读取到了excel文件4-6列3列..怎么把其中的两列(第四第六列)赋值给一个二维数组。非常感谢~
追问:array[i][j]里面的j数字一直在叠加 显示出来的数据是array[0][0]array[0][1]和array[1][2]array[1][3]。希望是array[1][0]和[1][1]怎么办呢?谢谢~
答案:根据你的代码改了下,输出没问题。
public class ReadTxt {

	public static void main(String[] args) {

		String filePath = "C:/1.xls";
		InputStream fs = null;
		Workbook workBook = null;
		String[][] array = null;
		try {
			fs = new FileInputStream(filePath);
			workBook = Workbook.getWorkbook(fs);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		int col = 0;
		int row = 0;
		Sheet[] sheets = workBook.getSheets();//获取sheet总数
		for (int n = 0; n < sheets.length; n++) {

			Sheet sheet = sheets[n];
			if (sheet.getRows() == 0) {//如果没数据则跳过
				continue;
			}
			array = new String[sheet.getRows() - 3][2];
			Cell cell = null;
			for (int j = 3; j < sheet.getRows(); j++) {
				row = 0;
				for (int i = 3; i < 6; i++) {
					cell = sheet.getCell(i, j);
					if (i != 4) {
						array[col][row] = cell.getContents();
						row++;
					}

				}
				col++;
			}
		}
		workBook.close();
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 2; j++) {
				System.out.println("array[" + i + "," + j + "]" + array[i][j]);
			}
		}
	}
}
其他:也是用的POI啊,是有问题

上一个:Java面向对象的程序设计思想是什么?
下一个:JAVA软件工程师是干什么?的写代码的吗?

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,