Fork me on GitHub

读取Excel列,转换为String输出(Java实现)

需要导入的jar包

具体实现

public class ColumnToString {
	public static void main(String[] args) {
        new ColumnToString().read();
    }

	public void read() {
	    File file = new File("Excel 文件位置(C:\\myExcel.xlsx)");
	    InputStream inputStream = null;
	    Workbook workbook = null;
	    try {
	        inputStream = new FileInputStream(file);
	        workbook = WorkbookFactory.create(inputStream);
	        inputStream.close();
	        //工作表对象
	        Sheet sheet = workbook.getSheetAt(0);
	        //总行数
	        int rowLength = sheet.getLastRowNum()+1;
	        //根据第一行,获取总列数
	        Row row = sheet.getRow(0);
	        //总列数
	        int colLength = row.getLastCellNum();
	        //得到指定的单元格
	        Cell cell = row.getCell(0);
	        System.out.println("行数:" + rowLength + ",列数:" + colLength);
	        ArrayList<String> list = new ArrayList<String>();
	        // 从第二行开始读取
	        for (int i = 1; i < rowLength; i++) {
	            row = sheet.getRow(i);
	            // 获取第二列的内容
	            cell = row.getCell(1);
	            if(cell != null){
	            	String temp = cell.getStringCellValue();
	            	if(temp != "EW_N" && !list.contains(temp)){
	            		list.add(temp);
	            	}
	            }
	        }
	        String result = ListToString(list);
	        System.out.println(list.size());
	        System.out.println(result);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	// List 集合转换为String
	public String ListToString(ArrayList<String> list){
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		for(int i = 0; i < list.size(); i++){
			// 最后一个元素不用加逗号
			if(i == list.size() - 1){
				sb.append("\'"+list.get(i)+"\'"+"\r\n");
			}else{
				sb.append("\'"+list.get(i)+"\'" + ","+"\r\n");
			}
		}
		sb.append(");");
		return sb.toString();
	}
}
posted @ 2018-08-28 09:50  小a的软件思考  阅读(5866)  评论(0编辑  收藏  举报