现在的位置: 首页 > 编程语言 > 正文

java读取cvs文件并导入数据库

2020年02月14日 编程语言 ⁄ 共 2084字 ⁄ 字号 评论关闭

本文实例为大家分享了java读取cvs文件并导入数据库的具体代码,供大家参考,具体内容如下

首先获取文件夹下面的所有类型相同的excel,可以用模糊匹配contains(“匹配字段”)

public static List getDictory(String path) { File f = new File(path); List<String> dictories = new ArrayList<String>(); if (!f.exists()) { System.out.println(path + "路径不存在"); } else { File fa[] = f.listFiles(); for (int i = 0; i < fa.length; i++) { File fs = fa[i]; if (!fs.isDirectory() && fs.getName().contains("csv")) { dictories.add(path + fs.getName()); } } System.out.println(dictories); } return dictories; }

操作jxl类型的excel表格需要导入一个jxl的jar包

private static void getExecl(Statement statement) { jxl.Workbook readwb = null; try { // 构建Workbook对象, 只读Workbook对象 // 直接从本地文件创建Workbook,根据实际情况更改文件路径 InputStream instream = new FileInputStream("文件路径"); readwb = Workbook.getWorkbook(instream); // Sheet的下标是从0开始 // 获取第一张Sheet表 Sheet readsheet = readwb.getSheet(0); // 获取Sheet表中所包含的总行数 int rsRows = readsheet.getRows(); // 循环获取excel的一行数据 for (int i = 2; i < rsRows; i++) { // System.out.println("\n"); // 获取需要导入数据库的单元格(列) int[] number = { 0, 4, 5, 7 }; Cell cell0 = readsheet.getCell(0, i);//第i行第一格 Cell cell4 = readsheet.getCell(4, i);//第i行第五格 Cell cell5 = readsheet.getCell(5, i);//第i行第六格 int id=cell0.getContents)();//获取第一格的数据 }readwb.close(); }catch (Exception e) { e.printStackTrace(); }}

但是有些从平台,后台之类的地方导出的excel是cvs类型。cvs是文本类型的文件,每一个单元格的数据使用“,”隔开。

public static void getExecl(Statement statement, String path) { try { BufferedReader reader = new BufferedReader(new FileReader(path));// 换成你的文件名 reader.readLine();// 第一行信息,为标题信息,不用,如果需要,注释掉 String line = null; String everyLine = null; List<String> list = new ArrayList<String>(); while ((line = reader.readLine()) != null) { // 行数 everyLine = line; list.add(everyLine); } // 读每一行数据 for (int i = 1; i < list.size(); i++) { // CSV格式文件为逗号分隔符文件,这里根据逗号切分 int j = 0; String item[] = list.get(i).split(","); } if (item[j] != null) { String id = item[0]; String datetime=item[8]; } } }

关于时间格式,excel中的时间需要格式化一下,才能导入数据库中相应的字段,而cvs的不用。前提是数据库中的字段是datetime类型的。

String ReceiveTime = null;if (cell11.getType() == CellType.DATE) { DateCell dc = (DateCell) cell11; Date date = dc.getDate(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ReceiveTime = sdf.format(date); }

最后连接数据库。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: java读取cvs文件并导入数据库

以上就上有关java读取cvs文件并导入数据库的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.