easyexcel: The maximum length of cell contents (text) is 32,767 characters


easyexcel The maximum length of cell contents (text) is 32,767 characters

 

使用easyexcel向excel中寫內容出現了單元格大小 不能超過32,767的限制,這是因為excel 2007限制單個cell不能超過32767個字符,但是現在都2020年了。。。。

 .xls和.xlsx文件格式有32,767個字符的硬限制. Apache POI只是強制執行Excel限制的文件格式.您可以在Microsoft文檔中查看這些限制的詳細信息,也可以在 this Apache POI javadoc page中很好地捕獲

將poi更新到最新版本仔細看看源碼 org.apache.poi.ss.SpreadsheetVersion 中只用excel97 和excel2007倆個選項 ,XSSFCell 類被修飾為final 不能被繼承重寫版本校驗方法。
 
解決辦法:
方法一:擴大最大值
在自己的項目文件夾下創建org.apache.poi.ss.SpreadsheetVersion 類,復制poi中的該類源碼,excel2007中的最后一個值改為int類型最大值。重試導出問題解決。

 

方法二:截取,分成多列存儲

 1 private static void writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
 2         int colIndex = 0;
 3 
 4         Font dataFont = wb.createFont();
 5         dataFont.setFontName("simsun");
 6         dataFont.setColor(IndexedColors.BLACK.index);
 7 
 8         XSSFCellStyle dataStyle = wb.createCellStyle();
 9         dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
10         dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
11         dataStyle.setFont(dataFont);
12         setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
13 
14         for (List<Object> rowData : rows) {
15             Row dataRow = sheet.createRow(rowIndex);
16             colIndex = 0;
17             for (Object cellData : rowData) {
18                 colIndex = setCell(cellData.toString(), dataRow, colIndex, dataStyle);
19             }
20             rowIndex++;
21         }
22     }
23 
24     private static int setCell(String data, Row dataRow, Integer colIndex, XSSFCellStyle dataStyle) {
25 
26         int max = 32767;
27         if (data == null || data.length() < max) {
28             Cell cell = dataRow.createCell(colIndex);
29             cell.setCellStyle(dataStyle);
30             cell.setCellValue(data == null ? "" : data);
31             colIndex++;
32         } else {
33             int num = data.length() / max;
34             for (int i = 0; i < num; i++) {
35                 Cell cell = dataRow.createCell(colIndex);
36                 cell.setCellStyle(dataStyle);
37                 cell.setCellValue(data.substring(i * max, max * (i + 1)));
38                 colIndex++;
39             }
40             int extra = data.length() % max;
41             if (extra > 0) {
42                 Cell cell = dataRow.createCell(colIndex);
43                 cell.setCellStyle(dataStyle);
44                 cell.setCellValue(data.substring(num * max, num * max + extra));
45                 colIndex++;
46             }
47         }
48         return colIndex;
49     }
示例

 

方法三:切換文件格式 (推薦)

如果您確實需要長文本,則需要切換到另一種文件格式,例如CSV

 

CSV是逗號分隔文件(Comma Separated Values)的首字母英文縮寫,是一種用來存儲數據的純文本格式,通常用於電子表格或數據庫軟件。在 CSV文件中,數據“欄”以逗號分隔,可允許程序通過讀取文件為數據重新創建正確的欄結構,並在每次遇到逗號時開始新的一欄。如:

1 ,張三,男
2 ,李四,男
3 ,小紅,女
  1 package com.yph.omp.common.util;
  2 
  3 import java.io.BufferedWriter;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileNotFoundException;
  7 import java.io.FileOutputStream;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.io.OutputStream;
 11 import java.io.OutputStreamWriter;
 12 import java.util.ArrayList;
 13 import java.util.Iterator;
 14 import java.util.LinkedHashMap;
 15 import java.util.List;
 16 import java.util.Map;
 17 
 18 import javax.servlet.http.HttpServletRequest;
 19 import javax.servlet.http.HttpServletResponse;
 20 
 21 import org.apache.commons.beanutils.BeanUtils;
 22 import org.junit.Test;
 23 
 24 /**
 25  * Java生成CSV文件
 26  */
 27 public class CSVUtil {
 28 
 29     /**
 30      * 生成為CVS文件
 31      * 
 32      * @param exportData
 33      *            源數據List
 34      * @param map
 35      *            csv文件的列表頭map
 36      * @param outPutPath
 37      *            文件路徑
 38      * @param fileName
 39      *            文件名稱
 40      * @return
 41      */
 42     @SuppressWarnings("rawtypes")
 43     public static File createCSVFile(List exportData, LinkedHashMap map,
 44             String outPutPath, String fileName) {
 45         File csvFile = null;
 46         BufferedWriter csvFileOutputStream = null;
 47         try {
 48             File file = new File(outPutPath);
 49             if (!file.exists()) {
 50                 file.mkdir();
 51             }
 52             // 定義文件名格式並創建
 53             csvFile = File.createTempFile(fileName, ".csv",
 54                     new File(outPutPath));
 55             // UTF-8使正確讀取分隔符","
 56             csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
 57                     new FileOutputStream(csvFile), "GBK"), 1024);
 58             // 寫入文件頭部
 59             for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
 60                     .hasNext();) {
 61                 java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
 62                         .next();
 63                 csvFileOutputStream
 64                         .write("\"" + (String) propertyEntry.getValue() != null ? (String) propertyEntry
 65                                 .getValue() : "" + "\"");
 66                 if (propertyIterator.hasNext()) {
 67                     csvFileOutputStream.write(",");
 68                 }
 69             }
 70             csvFileOutputStream.newLine();
 71             // 寫入文件內容
 72             for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
 73                 Object row = (Object) iterator.next();
 74                 for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
 75                         .hasNext();) {
 76                     java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
 77                             .next();            /*-------------------------------*/ 
 78                     //以下部分根據不同業務做出相應的更改
 79                     StringBuilder sbContext = new StringBuilder("");
 80                     if (null != BeanUtils.getProperty(row,(String) propertyEntry.getKey())) {
 81                         if("證件號碼".equals(propertyEntry.getValue())){
 82                             //避免:身份證號碼 ,讀取時變換為科學記數 - 解決辦法:加 \t(用Excel打開時,證件號碼超過15位后會自動默認科學記數)
 83                             sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t");
 84                         }else{
 85                             sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()));                            
 86                         }
 87                     }
 88                     csvFileOutputStream.write(sbContext.toString());
 89             /*-------------------------------*/                    
 90                     if (propertyIterator.hasNext()) {
 91                         csvFileOutputStream.write(",");
 92                     }
 93                 }
 94                 if (iterator.hasNext()) {
 95                     csvFileOutputStream.newLine();
 96                 }
 97             }
 98             csvFileOutputStream.flush();
 99         } catch (Exception e) {
100             e.printStackTrace();
101         } finally {
102             try {
103                 csvFileOutputStream.close();
104             } catch (IOException e) {
105                 e.printStackTrace();
106             }
107         }
108         return csvFile;
109     }
110 
111     /**
112      * 下載文件
113      * 
114      * @param response
115      * @param csvFilePath
116      *            文件路徑
117      * @param fileName
118      *            文件名稱
119      * @throws IOException
120      */
121     public static void exportFile(HttpServletRequest request,
122             HttpServletResponse response, String csvFilePath, String fileName)
123             throws IOException {
124         response.setCharacterEncoding("UTF-8");
125         response.setContentType("application/csv;charset=GBK");
126         
127         response.setHeader("Content-Disposition", "attachment; filename="
128                 + new String(fileName.getBytes("GB2312"), "ISO8859-1"));
129         InputStream in = null;
130         try {
131             in = new FileInputStream(csvFilePath);
132             int len = 0;
133             byte[] buffer = new byte[1024];
134             OutputStream out = response.getOutputStream();
135             while ((len = in.read(buffer)) > 0) {
136                 out.write(buffer, 0, len);
137             }
138         } catch (FileNotFoundException e1) {
139             System.out.println(e1);
140         } finally {
141             if (in != null) {
142                 try {
143                     in.close();
144                 } catch (Exception e1) {
145                     throw new RuntimeException(e1);
146                 }
147             }
148         }
149     }
150 
151     /**
152      * 刪除該目錄filePath下的所有文件
153      * 
154      * @param filePath
155      *            文件目錄路徑
156      */
157     public static void deleteFiles(String filePath) {
158         File file = new File(filePath);
159         if (file.exists()) {
160             File[] files = file.listFiles();
161             for (int i = 0; i < files.length; i++) {
162                 if (files[i].isFile()) {
163                     files[i].delete();
164                 }
165             }
166         }
167     }
168 
169     /**
170      * 刪除單個文件
171      * 
172      * @param filePath
173      *            文件目錄路徑
174      * @param fileName
175      *            文件名稱
176      */
177     public static void deleteFile(String filePath, String fileName) {
178         File file = new File(filePath);
179         if (file.exists()) {
180             File[] files = file.listFiles();
181             for (int i = 0; i < files.length; i++) {
182                 if (files[i].isFile()) {
183                     if (files[i].getName().equals(fileName)) {
184                         files[i].delete();
185                         return;
186                     }
187                 }
188             }
189         }
190     }
191 
192     @SuppressWarnings({ "unchecked", "rawtypes" })
193     @Test
194     public void createFileTest() {
195         List exportData = new ArrayList<Map>();
196         Map row1 = new LinkedHashMap<String, String>();
197         row1.put("1", "11");
198         row1.put("2", "12");
199         row1.put("3", "13");
200         row1.put("4", "14");
201         exportData.add(row1);
202         row1 = new LinkedHashMap<String, String>();
203         row1.put("1", "21");
204         row1.put("2", "22");
205         row1.put("3", "23");
206         row1.put("4", "24");
207         exportData.add(row1);
208         LinkedHashMap map = new LinkedHashMap();
209         map.put("1", "第一列");
210         map.put("2", "第二列");
211         map.put("3", "第三列");
212         map.put("4", "第四列");
213 
214         String path = "d:/export";
215         String fileName = "文件導出";
216         File file = CSVUtil.createCSVFile(exportData, map, path, fileName);
217         String fileNameNew = file.getName();
218         String pathNew = file.getPath();
219         System.out.println("文件名稱:" + fileNameNew );
220         System.out.println("文件路徑:" + pathNew );
221     }
222 }//注:BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t" ,只為解決數字格式超過15位后,在Excel中打開展示科學記數問題。
Java生成CSV文件

 

參考:
https://www.jianshu.com/p/9e73399b6c38 
http://www.voidcn.com/article/p-wrsnsvtm-bxy.html
https://www.cnblogs.com/bailuobo/p/4911764.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM