話不多說,請看代碼:
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
|
import java.io.*; import jxl.*; import jxl.write.*; //用java將txt數據導入excel public class CreateXLS { public static void main(String args[]) { try { //打開文件 WritableWorkbook book= Workbook.createWorkbook( new File( "測試.xls" )); //生成名為“第一頁”的工作表,參數0表示這是第一頁 WritableSheet sheet=book.createSheet( "第一頁" , 0 ); //在Label對象的構造子中指名單元格位置是第一列第一行(0,0) //以及單元格內容為test Label label= new Label( 0 , 0 , "test" ); //將定義好的單元格添加到工作表中 sheet.addCell(label); /*生成一個保存數字的單元格 必須使用Number的完整包路徑,否則有語法歧義 單元格位置是第二列,第一行,值為789.123*/ jxl.write.Number number = new jxl.write.Number( 1 , 0 , 789.123 ); sheet.addCell(number); //寫入數據并關閉文件 book.write(); book.close(); } catch (Exception e) { System.out.println(e); } } } |
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
|
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; //用java將excel數據導入txt public class WriteTxt { public static void main(String[] args) { // TODO Auto-generated method stub String filepath = "d:\\demo.xls" ; try { Workbook workbook = Workbook.getWorkbook( new File(filepath)); Sheet sheet = workbook.getSheet( 0 ); File file = new File( "d:/1.txt" ); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); // j為行數,getCell("列號","行號") int j = sheet.getRows(); int y = sheet.getColumns(); for ( int i = 0 ; i < j; i++) { for ( int x= 0 ; x<y; x++){ Cell c = sheet.getCell(x, i); String s = c.getContents(); bw.write(s); bw.write( " " ); bw.flush(); } bw.newLine(); bw.flush(); } System.out.println( "寫入結束" ); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
遇到的問題:
txt文件中單元格數據之間用|分割,用string.split("\\|");提取數據
用的jar包對excel2007不支持 從而導致轉換出的是空文件
excel文件轉txt文件時,用tab鍵分隔 分隔字符串數組時用String.split("\\ ",-1);
上線遇到的問題:
1.在windows上獲取路徑地址是以\分隔的,而在linux上獲取的路徑是以/分隔的,這要注意
2.默認情況下,Excel中每個單元格所能顯示的數字為11位,輸入超過11位的數值,系統自動將其轉換為科學記數格式,當txt轉excel時,有兩種方法可以解決這個問題,第一種是在單元格數字前加個單引號,第二種是設置單元格的格式為文本格式,在上述代碼中加入以下代碼
1
2
3
4
5
6
7
8
9
|
WritableFont wf = new WritableFont(WritableFont.TIMES, 12 ,WritableFont.NO_BOLD, false ); WritableCellFormat wcfF = new WritableCellFormat(NumberFormats.TEXT); wcfF.setFont(wf); CellView cv = new CellView(); cv.setFormat(wcfF); cv.setSize( 10 * 265 ); sheet.setColumnView(j, cv); Label label = new Label(j,n,s1[j]); sheet.addCell(label); |
3. 當txt轉excel在windows上轉換成功時,到linux服務器上轉出的excel中漢字變成了亂碼,因為FileWriter fw = new FileWriter(file);
這句代碼采用默認字符集解析,經過嘗試,使用GBK解析文件,用以下代碼可不出現亂碼,
1
|
BufferedReader bw = new BufferedReader( new InputStreamReader( new FileInputStream( new File(filen)), "GBK" )); |
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家
原文鏈接:http://www.cnblogs.com/hy168/p/5842353.html