前言
本文主要給大家介紹的是關于Java對xls文件進行讀寫操作的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹:
- win7_x64
- IDEA
Java讀寫xls文件,使用庫jxl.jar
讀寫xls文件,這里是在知道表格格式的前提下進行操作的。
目前無法操作xlsx文件
準備工作
將庫jxl.jar添加到工程依賴中
Java代碼示例
示例:從幾個文件中讀取數據并匯總到一個文件中
表格中的數據規定為:首行為標題,以下是數據和名稱;例如
1
2
3
4
|
單位名 金額 單位1 948.34 單位2 4324 單位5 324 |
準備好表格文件,放在指定目錄下
示例過程大致為:在指定目錄找到所有xls文件;遍歷所有文件,讀取出所有的單位名稱;將單位名稱排序;再遍歷一次所有文件,將每個文件中單位對應的金額讀出并存儲;最后寫到輸出表格中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
final String wsFileDir = "H:/OtherWorkDocs/ws" ; // 原始數據存放的目錄 final String resFilePath = "H:/OtherWorkDocs/output/jan_feb_mar_sum.xls" ; RWExcel rwExcel = new RWExcel(); // 操作xls的實例 // 獲取所有的名稱并排序 TreeSet<String> nameSet = rwExcel.getNameSet(wsFileDir); // 將名稱與下標存入map中 HashMap<String, Integer> nameRowHashMap = rwExcel.getNameRowHashMap(nameSet); File wsDir = new File(wsFileDir); // 源文件目錄 File[] sourceFiles = wsDir.listFiles(); // 存儲單位名稱與金額對應的數據 List<HashMap<String, Float>> dataList = new ArrayList<>( 10 ); if (sourceFiles != null ) { for (File sF : sourceFiles) { // 裝載數據 dataList.add(rwExcel.getSourceData(sF.getAbsolutePath())); } } // 原始數據已經全部讀出來,和名稱一次性全部寫入 rwExcel.writeAllToResFile(resFilePath, nameRowHashMap, dataList); // 補充標題欄的標題 if ( null != sourceFiles) { int col = 1 ; // 起始列的序號 for (File f : sourceFiles) { String fileName = f.getName(); String name = fileName.substring( 0 , fileName.length() - 4 ); rwExcel.updateContent(resFilePath, name, 0 , col); col++; } } |
Java代碼
新建一個類RWExcel來操作xls文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
public class RWExcel { /** * 存儲名稱 */ private TreeSet<String> nameTreeSet = new TreeSet<>(); /** * 名稱以及排列的下標號 */ private HashMap<String, Integer> nameRowMap = new HashMap<>(); public TreeSet<String> getNameSet(String wsPath) { try { File wsDir = new File(wsPath); if (wsDir.exists() && wsDir.isDirectory()) { println( "工作目錄存在" ); File[] files = wsDir.listFiles(); if (files != null && files.length > 0 ) { for (File cFile : files) { getNamesFromFile(cFile, this .nameTreeSet); } } } } catch (Exception e) { e.printStackTrace(); } this .nameTreeSet.comparator(); return this .nameTreeSet; } /** * 將名稱Set排序后存入HashMap * 下標從1開始 */ public HashMap<String, Integer> getNameRowHashMap(TreeSet<String> nameSet) { nameSet.comparator(); int index = 1 ; for (String name : nameSet) { this .nameRowMap.put(name, index); index++; } return this .nameRowMap; } /** * 所有數據存入表格 */ public void writeAllToResFile(String resFilePath, Map<String, Integer> nameMap, List<HashMap<String, Float>> dataList) { File resFile = new File(resFilePath); if (!resFile.exists()) { try { resFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if (resFile.exists()) { try { // 先寫名稱 WritableWorkbook wwb = Workbook.createWorkbook(resFile); WritableSheet ws = wwb.createSheet( "sum" , 0 ); Label label = new Label( 0 , 0 , "單位名稱" ); ws.addCell(label); for (Map.Entry<String, Integer> entry : nameMap.entrySet()) { Label nameLabel = new Label( 0 , entry.getValue(), entry.getKey()); ws.addCell(nameLabel); for ( int j = 0 ; j < dataList.size(); j++) { Number zeroCell = new Number(j + 1 , entry.getValue(), 0 ); ws.addCell(zeroCell); } } for ( int dataColumn = 0 ; dataColumn < dataList.size(); dataColumn++) { HashMap<String, Float> dataMap = dataList.get(dataColumn); // 遍歷這個map 將所有的數據對應填入 for (Map.Entry<String, Float> dataEntry : dataMap.entrySet()) { int row = nameRowMap.get(dataEntry.getKey()); Number numberCell = new Number(dataColumn + 1 , row, dataEntry.getValue()); ws.addCell(numberCell); } } wwb.write(); wwb.close(); } catch (Exception e) { e.printStackTrace(); } } } private void getNamesFromFile(File inputFile, TreeSet<String> hashSet) throws IOException, BiffException { Workbook workbook; InputStream is = new FileInputStream(inputFile); workbook = Workbook.getWorkbook(is); Sheet sheet0 = workbook.getSheet( 0 ); int columnSum = sheet0.getColumns(); // 總列數 int rsRows = sheet0.getRows(); // 總行數 // 從1下標開始 for ( int i = 1 ; i < rsRows; i++) { Cell cell = sheet0.getCell( 0 , i); if (!isEmpty(cell.getContents())) { hashSet.add(cell.getContents()); } } println( "此文件行數減一 = " + (rsRows - 1 ) + " , 當前獲取到的所有單位數 " + hashSet.size()); } /** * 從原始數據中讀取并匹配的存入結果文件中 */ private HashMap<String, Float> getSourceData(String source) { File sFile = new File(source); if (!sFile.exists()) { System.out.println( "原始文件不存在 復制失敗!" ); return null ; } // 讀取源文件中的所有數據 <單位名稱, 數值> HashMap<String, Float> sourceHashMap = new HashMap<>(); try { Workbook sourceWs = Workbook.getWorkbook(sFile); Sheet sSheet0 = sourceWs.getSheet( 0 ); int sTotalRows = sSheet0.getRows(); // 總行數 for ( int i = 1 ; i < sTotalRows; i++) { Cell cellKey = sSheet0.getCell( 0 , i); Cell cellValue = sSheet0.getCell( 1 , i); if (!isEmpty(cellKey.getContents()) && !isEmpty(cellValue.getContents())) { sourceHashMap.put(cellKey.getContents(), Float.valueOf(cellValue.getContents())); } } println(source + " 讀取到的數據數量 = " + sourceHashMap.size()); } catch (Exception e) { e.printStackTrace(); } return sourceHashMap; } public void updateContent(String filePath, String input, int row, int column) { File file = new File(filePath); if (!file.exists()) { System.out.println(filePath + " does not exist!" ); return ; } try { Workbook sourceWb = Workbook.getWorkbook(file); WritableWorkbook wwb = Workbook.createWorkbook(file, sourceWb); WritableSheet wSheet0 = wwb.getSheet( 0 ); Label label = new Label(column, row, input); wSheet0.addCell(label); wwb.write(); wwb.close(); } catch (Exception e) { e.printStackTrace(); } } public RWExcel() { } private static boolean isEmpty(String str) { if ( null == str) { return true ; } return str.isEmpty(); } private static void println(String in) { System.out.println(in); } } |
示例運行結果
得到以下結果(示例)
1
2
3
4
5
6
7
8
9
10
|
單位名稱 1月總金額 2月總金額 3月總金額 單位1 0 59.29999924 948.3400269 單位10 0 0 494.2000122 單位11 0 0 11.19999981 單位12 0 0 1.25 單位15 49.36000061 0 0 單位2 0 0 4324 單位24 0 34 0 單位5 0 23123 324 單位6 0 161.2599945 0 |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://rustfisher.github.io/2017/04/18/Java_note/Java-read-write-xls/