Java ConcurrentModificationException 在写入Excel时发生的错误。

huangapple go评论114阅读模式
英文:

Java ConcurrentModificationException Error while writing in Excel

问题

以下是您要翻译的代码部分:

  1. 我有一个Java我使用它来根据输入在特定单元格中写入特定字符串
  2. 我使用Apache POI
  3. 我的类有两个写入方法一个用于单行写入另一个用于多次写入
  4. 多次写入的方法似乎是我的问题我认为 :(
  5. 这是我的写入类
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.OutputStream;
  12. import java.util.Iterator;
  13. import org.apache.poi.ss.usermodel.Cell;
  14. import org.apache.poi.ss.usermodel.CellType;
  15. import org.apache.poi.ss.usermodel.Row;
  16. import org.apache.poi.xssf.usermodel.XSSFRow;
  17. import org.apache.poi.xssf.usermodel.XSSFSheet;
  18. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  19. public class TrueExcelWriter {
  20. public TrueExcelWriter(){}
  21. private static int findRow(XSSFSheet sheet, String cellContent) {
  22. for (Row row : sheet) {
  23. for (Cell cell : row) {
  24. if (cell.getCellType() == CellType.STRING) {
  25. if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
  26. return row.getRowNum();
  27. }
  28. }
  29. if (cell.getCellType().equals(CellType.NUMERIC)){
  30. long lookup = (long) cell.getNumericCellValue();
  31. String catcher = Long.toString(lookup);
  32. if(catcher.equals(cellContent)){
  33. return row.getRowNum();
  34. }
  35. }
  36. }
  37. }
  38. return 0;
  39. }
  40. public void WriteToAll(String suchobjekt, String ID, String SPID) throws FileNotFoundException, IOException{
  41. final String fileName = "C:/Temp/TTT.xlsx";
  42. InputStream input = new FileInputStream(fileName);
  43. XSSFWorkbook wb = new XSSFWorkbook(input);
  44. XSSFSheet sheet = wb.getSheetAt(0);
  45. int colnr = 0;
  46. switch (suchobjekt) {
  47. case "option1":
  48. colnr = 15;
  49. break;
  50. case "option2":
  51. colnr = 16;
  52. break;
  53. case "option3":
  54. colnr = 999;
  55. break;
  56. }
  57. Iterator<Row> iterator = sheet.iterator();
  58. while (iterator.hasNext()) {
  59. Row nextRow = iterator.next();
  60. if(nextRow.getRowNum()==0){
  61. continue; //just skip the rows if row number is X or Y
  62. }
  63. Iterator<Cell> cellIterator = nextRow.cellIterator();
  64. while (cellIterator.hasNext()) {
  65. Cell nextCell = cellIterator.next();
  66. String y = nextCell + "";
  67. if(y.equals(ID)){
  68. Row r = sheet.getRow(nextRow.getRowNum());
  69. if (r == null) {
  70. r = sheet.createRow(nextRow.getRowNum());
  71. }
  72. Cell c = r.getCell(colnr);
  73. if (c == null) {
  74. c = r.createCell(colnr, CellType.STRING);
  75. }
  76. c.setCellValue(SPID);
  77. }
  78. }
  79. }
  80. input.close();
  81. OutputStream output = new FileOutputStream(fileName);
  82. wb.write(output);
  83. output.close();
  84. wb.close();
  85. }
  86. public void WriteTo(String suchobjekt, String ID, String SPID) throws FileNotFoundException, IOException{
  87. final String fileName = "C:/Temp/TTT.xlsx";
  88. InputStream input = new FileInputStream(fileName);
  89. XSSFWorkbook wb = new XSSFWorkbook(input);
  90. XSSFSheet sheet = wb.getSheetAt(0);
  91. int colnr = 0;
  92. int rownr;
  93. switch (suchobjekt) {
  94. case "option1":
  95. colnr = 15;
  96. break;
  97. case "option2":
  98. colnr = 16;
  99. break;
  100. case "option3":
  101. colnr = 999;
  102. break;
  103. }
  104. rownr = findRow(sheet, ID);
  105. Row r = sheet.getRow(rownr);
  106. if (r == null) {
  107. r = sheet.createRow(rownr);
  108. }
  109. Cell c = r.getCell(colnr);
  110. if (c == null) {
  111. c = r.createCell(colnr, CellType.STRING);
  112. }
  113. c.setCellValue(SPID);
  114. input.close();
  115. OutputStream output = new FileOutputStream(fileName);
  116. wb.write(output);
  117. output.close();
  118. wb.close();
  119. }
  120. }

我正在使用以下代码在我的Excel文件中写入内容:

  1. try {
  2. ter.WriteToAll("option2", "abc", "done");
  3. } catch (IOException ex) {
  4. System.out.println("Error! "+ex);
  5. }

我的Excel文件当前如下所示:

  1. ...14 15 16 ...
  2. ... | ID | ...
  3. ... | abc | done
  4. ... | abc | done
  5. ... | abc | done
  6. ... | def |
  7. ... | ghi |
  8. ... | jkl |
  9. ... | jkl |
  10. ... | jkl |
  11. ... | mno |
  12. ... | mno |
  13. ... | mno |

如果我使用上面的方法并将其用于所有ID,一切都可以正常工作,除了ID "def"!

我不知道为什么这对这一个不起作用。 Java ConcurrentModificationException 在写入Excel时发生的错误。

如果我尝试使用单行写入函数来处理此ID,它可以正常工作。

但我不知道为什么多行写入函数对这一个不起作用。

我收到以下错误消息:

  1. Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
  2. at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
  3. at java.base/java.util.TreeMap$ValueIterator.next(TreeMap.java:1253)
  4. at easypackaging.TrueExcelWriter.WriteToAll(TrueExcelWriter.java:88)
  5. at easypackaging.TEST_TrueVerladen.actionPerformed(TEST_TrueVerladen.java:172)
  6. at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
  7. at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
  8. at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
  9. at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
  10. at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
  11. at java.desktop/java.awt.Component.processMouseEvent(Component.java:6636)
  12. at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
  13. at java.desktop/java.awt.Component.processEvent(Component.java:6401)
  14. at java.desktop/java.awt.Container.processEvent(Container.java:2263)
  15. at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5012)
  16. at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
  17. at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
  18. at java.desktop/java.awt.LightweightDispatcher.retarget
  19. <details>
  20. <summary>英文:</summary>
  21. I have a java class which I use to write a specific String in a specific cell, depending on the input.
  22. I use Apache POI.
  23. My Class has two writing methods. One for single line writing and one for writing multiple times.
  24. The method for multiple writing seems to be my trouble, I think :(
  25. here is my writing class:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TrueExcelWriter {

  1. public TrueExcelWriter(){}
  2. private static int findRow(XSSFSheet sheet, String cellContent) {
  3. for (Row row : sheet) {
  4. for (Cell cell : row) {
  5. if (cell.getCellType() == CellType.STRING) {
  6. if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
  7. return row.getRowNum();
  8. }
  9. }
  10. if (cell.getCellType().equals(CellType.NUMERIC)){

// if (DateUtil.isCellDateFormatted(cell)) {
// System.out.println(cell.getDateCellValue());
//
// } else {
long lookup = (long) cell.getNumericCellValue();
String catcher = Long.toString(lookup);

  1. if(catcher.equals(cellContent)){
  2. return row.getRowNum();
  3. }

// }

  1. }
  2. }
  3. }
  4. return 0;
  5. }
  6. public void WriteToAll(String suchobjekt, String ID, String SPID) throws FileNotFoundException, IOException{
  7. final String fileName = &quot;C:/Temp/TTT.xlsx&quot;;
  8. InputStream input = new FileInputStream(fileName);
  9. XSSFWorkbook wb = new XSSFWorkbook(input);
  10. XSSFSheet sheet = wb.getSheetAt(0);
  11. int colnr = 0;
  12. switch (suchobjekt) {
  13. case &quot;option1&quot;:
  14. colnr = 15;
  15. break;
  16. case &quot;option2&quot;:
  17. colnr = 16;
  18. break;
  19. case &quot;option3&quot;:
  20. colnr = 999;
  21. break;
  22. }
  23. Iterator&lt;Row&gt; iterator = sheet.iterator();
  24. while (iterator.hasNext()) {
  25. Row nextRow = iterator.next();
  26. if(nextRow.getRowNum()==0){
  27. continue; //just skip the rows if row number is X or Y
  28. }
  29. Iterator&lt;Cell&gt; cellIterator = nextRow.cellIterator();
  30. while (cellIterator.hasNext()) {
  31. Cell nextCell = cellIterator.next();
  32. String y = nextCell + &quot;&quot;;
  33. if(y.equals(ID)){
  34. Row r = sheet.getRow(nextRow.getRowNum());
  35. if (r == null) {
  36. // First cell in the row, create
  37. r = sheet.createRow(nextRow.getRowNum());
  38. }
  39. Cell c = r.getCell(colnr);
  40. if (c == null) {
  41. // New cell
  42. c = r.createCell(colnr, CellType.STRING);
  43. }
  44. c.setCellValue(SPID);
  45. }
  46. }
  47. }
  48. input.close();
  49. OutputStream output = new FileOutputStream(fileName);
  50. wb.write(output);
  51. output.close();
  52. wb.close();
  53. }
  54. public void WriteTo(String suchobjekt, String ID, String SPID) throws FileNotFoundException, IOException{
  55. final String fileName = &quot;C:/Temp/TTT.xlsx&quot;;
  56. InputStream input = new FileInputStream(fileName);
  57. XSSFWorkbook wb = new XSSFWorkbook(input);
  58. XSSFSheet sheet = wb.getSheetAt(0);
  59. int colnr = 0;
  60. int rownr;
  61. switch (suchobjekt) {
  62. case &quot;option1&quot;:
  63. colnr = 15;
  64. break;
  65. case &quot;option2&quot;:
  66. colnr = 16;
  67. break;
  68. case &quot;option3&quot;:
  69. colnr = 999;
  70. break;
  71. }
  72. rownr = findRow(sheet, ID);
  73. Row r = sheet.getRow(rownr);
  74. if (r == null) {
  75. // First cell in the row, create
  76. r = sheet.createRow(rownr);
  77. }
  78. Cell c = r.getCell(colnr);
  79. if (c == null) {
  80. // New cell
  81. c = r.createCell(colnr, CellType.STRING);
  82. }
  83. c.setCellValue(SPID);
  84. input.close();
  85. OutputStream output = new FileOutputStream(fileName);
  86. wb.write(output);
  87. output.close();
  88. wb.close();
  89. }

}

  1. I am using the following code to write something in my excel file:

try {
ter.WriteToAll("option2", "abc", "done");
} catch (IOException ex) {
System.out.println("Error! "+ex);
}

  1. My excel file currently looks like this:

...14 15 16 ...
... | ID | ...
... | abc | done
... | abc | done
... | abc | done
... | def |
... | ghi |
... | jkl |
... | jkl |
... | jkl |
... | mno |
... | mno |
... | mno |

  1. If I use the method from above and used it for all IDs, everything works **except** for ID &quot;***def***&quot;!
  2. I don&#39;t know why this does not work for this single one. :(
  3. If I try the single line writing function for this ID, it works.
  4. But I font know why the multiple writing function does not work for this one.
  5. I am getting the following error message:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
at java.base/java.util.TreeMap$ValueIterator.next(TreeMap.java:1253)
at easypackaging.TrueExcelWriter.WriteToAll(TrueExcelWriter.java:88)
at easypackaging.TEST_TrueVerladen.actionPerformed(TEST_TrueVerladen.java:172)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6636)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6401)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5012)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2762)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

  1. `TrueExcelWriter` is the class where I run the `ter.WriteToAll`.
  2. I googled the error but I was not able to solve my problem with what I found. :(
  3. If needed, I can upload my complete (censored) excel sheet for you.
  4. Can you guys help me out?
  5. Sincerely yours,
  6. Shathos
  7. **UPDATE:**
  8. I wrote a new, simpler algorithm for my multiple line writing which worked for me. :) Thank&#39;s for the help!
  9. New function:

public void WriteToAll_TV(String ID, String SPID) throws FileNotFoundException, IOException{

  1. final String fileName = &quot;C:/Temp/TTT.xlsx&quot;;
  2. InputStream input = new FileInputStream(fileName);
  3. XSSFWorkbook wb = new XSSFWorkbook(input);
  4. CreationHelper createHelper = wb.getCreationHelper();
  5. XSSFSheet sheet = wb.getSheetAt(0);
  6. XSSFCell cell;
  7. XSSFRow row;
  8. int colnr = 15;
  9. int rownr = 0;
  10. rownr = findRow(sheet, ID);
  11. for(int i = rownr; i &lt; sheet.getLastRowNum(); i++){
  12. row = sheet.getRow(i);
  13. String y = row.getCell(colnr)+&quot;&quot;;
  14. if(y.equals(ID)){
  15. row.createCell(16).setCellValue(createHelper.createRichTextString(SPID));
  16. }
  17. }
  18. input.close();
  19. OutputStream output = new FileOutputStream(fileName);
  20. wb.write(output);
  21. output.close();
  22. wb.close();
  23. }
  1. </details>
  2. # 答案1
  3. **得分**: 1
  4. 你在遍历行时添加行来修改表格,这就是导致ConcurrentModificationException异常的原因。
  5. <details>
  6. <summary>英文:</summary>
  7. You are modifying the sheet by adding rows while iterating over the rows. That is where the ConcurrentModificationException is coming from.
  8. </details>

huangapple
  • 本文由 发表于 2020年8月9日 09:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63321549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定