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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZoeYen_/article/details/84541389
首先获取文件夹下面的所有类型相同的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);
					}
最后连接数据库

猜你喜欢

转载自blog.csdn.net/ZoeYen_/article/details/84541389