本文實例為大家分享了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);
}
最后連接數據庫。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。