java讀取excel表格的方法
阿新 • • 發佈:2021-01-04
在使用java的時候,希望從excel中讀取到一些單元格的資料,供大家參考,具體內容如下
1.Java讀取的excel的api
這裡用到了一個叫jxl的api如下:
<dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency>
在java中需要去匯入一些類去讀取excel
import jxl.Workbook; //java讀取excel表使用的類 import jxl.Cell; //java讀取表格裡的單元格的類 import jxl.Sheet; //java讀取的工作鋪的類
首先:
建立一個File 去讀取檔案(我以D盤redisInput檔案下的GPSINFO.xls檔案為例)
注意:不能夠讀取xlsx字尾的excel檔案,否則會報錯: Unable to recognize OLE stream
File Inputfile = new File("D:\\redisInput\\GPSINFO.xls");
使用字元流去接File的資料
FileInputStream fileInputStream = new FileInputStream(Inputfile);
workbook去接fileInputStream
Workbook workbook = Workbook.getWorkbook(fileInputStream);
這樣讀取到了excel檔案,但是需要去判斷是哪一個工作簿,要用到Sheet類
Sheet readfirst = workbook.getSheet(0);
如果getsheet(0)那麼就是去訪問第一個工作簿裡的資料,然後可以在sheet類中看有多少有效行和有效列
int rows = readfirst.getRows(); int clomns = readfirst.getColumns(); System.out.println("row:" + rows); System.out.println("clomns:" + clomns);
如果想看每個單元格的資料可以使用一個雙重迴圈去讀取每一個有效單元格里資料
for(int i =1;i<rows;i++) { for(int j =1;i<rows;i++) { Cell cell = readfirst.getCell(j,i); //j在前 i 在後是根據excel下標來判斷的 String s = cell.getContents(); System.out.println("cell"+s); }
這樣就把所有的有效單元格輸出了。
2.讀到的單元格進行列印
但是我想讓它按照我想要的格式進行輸出,比如 excel表中有sim卡 ,車牌號,終端號,我希望讓它能夠生成一個特有的格式讓我使用比如:
轉成-》這種格式的資料
所以一個完整過程如下:
public class AnalysisExcel { Workbook workbook = null; File Inputfile = new File("D:\\redisInput\\GPSINFO.xls"); File outputfile =new File("D:\\redisInput\\GPSINFO.txt"); public void ToAnalysisExcel() { // Unable to recognize OLE stream 不支援xlsx格式 支援xls格式 try { FileInputStream fileInputStream = new FileInputStream(Inputfile); workbook = Workbook.getWorkbook(fileInputStream); FileOutputStream fileOutputStream = new FileOutputStream(outputfile); BufferedOutputStream bw = new BufferedOutputStream(fileOutputStream); //輸出語句 Sheet readfirst = workbook.getSheet(0); int rows = readfirst.getRows(); int clomns = readfirst.getColumns(); System.out.println("row:" + rows); System.out.println("clomns:" + clomns); for(int i =1;i<rows;i++) { Cell[] cells = readfirst.getRow(i); //迴圈得到每一行的單元格物件 //根據每一個單元格物件的到裡面的值 String brandNum= cells[0].getContents(); String deviceCode = cells[1].getContents(); String sim =cells[2].getContents(); System.out.println("rand:"+brandNum+",vehicleNum:"+deviceCode+",sim:"+sim); //將得到的值放在一個我需要的格式的string物件中 String output = "\n"+sim+"\n" + "{\n" + " \"brandColor\": 500000,\n" + " \"brandNumber\": \""+brandNum+"\",\n" + " \"deviceCode\": \""+deviceCode+"\",\n" + " \"simCard\": \""+sim+"\"\n" + "}"+ "\n"; //write and flush到 我需要的檔案中去,flush後才能成功 byte[] outputbyte = new String(output).getBytes(); bw.write(outputbyte); bw.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。