700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java读取txt文件 excel文件的方法

Java读取txt文件 excel文件的方法

时间:2023-07-03 16:17:06

相关推荐

Java读取txt文件 excel文件的方法

Java读取txt文件、excel文件的方法

1.读取txt文件

public static String getFileContent(String filePath,String charset){//filePath为文件路径,charset为字符编码。通常使用UTF-8File file = new File(filePath);BufferedReader reader = null;String tempString = null;int line =1;StringBuffer str = new StringBuffer();try {log.error("以行为单位读取文件内容,一次读一整行:");InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charset); reader = new BufferedReader(isr);while ((tempString = reader.readLine()) != null) {//log.info("Line"+ line + ":" +tempString);str.append(tempString + "\r\n");line ++ ;}reader.close();} catch (FileNotFoundException e) {log.error("文件不存在:",e);} catch (IOException e) {// TODO Auto-generated catch blocklog.error("文件读取异常:",e);}finally{if(reader != null){try {reader.close();} catch (IOException e) {log.error("文件读取异常:",e);}}}System.out.println(str.toString());return str.toString();}

读取的数据为一行一行的字符串,可以使用String接收,使用split切分,获取自己需要的数据,举例如下:

String response = FileHelper.getFileContent(fileUrl,"UTF-8");if(!StringUtil.isEmptyStr(response)){String[] sz = response.split("\\n");Map<String,Object> statementMap = null;List<Map<String,Object>> statementList = new ArrayList<Map<String,Object>>();for (int i = 0; i < sz.length; i++){statementMap = new HashMap<String,Object>();String[] statement = sz[i].split("\\|\\|\\|",-1);String account = statement[0];String figer = statement[1];String number = statement[2];String proName = statement[3];String expTime = statement[4];statementMap.put("account", account);statementMap.put("figer", figer);statementMap.put("number", number);statementMap.put("proName", proName);statementMap.put("expTime", expTime);statementList.add(statementMap);}resultMap.put("list", statementList);

2.读取excel文件

/** 获取excel某列数据方法*/public static List<String> readExcel(String filePath){File file = new File(filePath);List<String> headList = new ArrayList<>();InputStream in = null;try {in = new FileInputStream(file);XSSFWorkbook wb = new XSSFWorkbook(in);XSSFSheet sheet = wb.getSheetAt(0); //获取第一张工作表int firstRowNum = sheet.getFirstRowNum();int lastRowNum = sheet.getLastRowNum();XSSFRow row = sheet.getRow(sheet.getFirstRowNum());//判断表行是否为空if (null == row){//表空,直接返回return headList;}for (int i = firstRowNum + 1; i <= lastRowNum; i++) {//遍历行,第一行为表头,跳过row = sheet.getRow(i);XSSFCell cell = row.getCell(0);//取每行的第一列数据,可根据需要修改或者遍历if (StrHelper.isNotEmpty(cell.getStringCellValue().trim())){headList.add(cell.getStringCellValue().trim());System.out.println(cell.getStringCellValue().trim());}}in.close();} catch (Exception e) {e.printStackTrace();} finally{try {if(in != null){in.close();}} catch (IOException e) {e.printStackTrace();}}return headList;}

读取的数据为String数组,可以使用List接收,获取自己需要的数据,举例如下:

List<String> response = FileHelper.readExcel(fileUrl);

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