[英]How to splitting records based white spaces when different lines have spaces at different positions
[英]How to Divide the data in excel sheet which have different white spaces
我正在使用Java從Excel工作表中獲取數據。 我必須將Excel工作表的每一行分開,並將它們分別存儲到數組Item1
, Item2
, Item3
, Item4
。
1. Item1 Item2 Item3 Item4 2. 104F410 020544E0 1120D3614 HD434816N 43X48 16-MIC CLEAR Runas 3. Promo 1343u 548548T 3465689634 HD404816N 40X48 16-MIC CLEAR
(等等)
我使用了以下代碼,但它錯誤地獲取了Item,如Item2
和Item3
作為Item
for (int realel = 0; realel < fouritems.size(); realel++) {
System.out.println("4 elements can be splitted from :" + fouritems.get(realel));
}
headitems2 = new String[fouritems.size()];
int f = 0;
for (int realel1 = 0; realel1 < fouritems.size(); realel1++) {
headitems2 = fouritems.get(realel1).split("\\s+");
try {
Item1.add(headitems2[0]);
System.out.println("Item1 :" + Item1.get(f));
Item2.add(item1[1]);
System.out.println("Item2 :" + VendorItem.get(f));
Item3.add(items3[2]);
System.out.println("Item3 :" + Item3.get(f));
f++;
} catch (Exception e) {
}
}
關於如何解決此問題的任何想法?
幾年前,我使用了Apache POI(Microsoft文檔的Java API)來處理Excel文件。 您可以使用API通過Cell類的getStringCellValue直接從表中獲取數據。 這將很好地處理普通Excel工作表。 如果您的Excel文件包含許多精美功能或VBA代碼,則可能會遇到麻煩。
假設所有單元格的格式都為“文本/字符串”,則下面的代碼將讀取Excel工作表的內容。 在這種情況下,您必須讀取數值,必須使用getNumericCellValue()而不是getStringCellValue()。
import java.io.File;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
public class ReadFromXLS {
public static void main(String[] args) throws InvalidFormatException, IOException {
File xlFile = new File("MyInput.xls");
Workbook wb = WorkbookFactory.create(xlFile);
Sheet sheet = wb.getSheet("Sheet1");
Row row = null;
Cell cell = null;
String value = null;
StringBuffer sb = new StringBuffer(100);
for (int i = 1; i <= 2; i++) {
row = sheet.getRow(i);
for (int j=0; j <= 3; j++) {
cell = row.getCell(j);
value = cell.getStringCellValue();
sb.append(";").append(value);
}
System.out.println(sb.substring(1));
sb = new StringBuffer(100);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.