我目前正在将excel数据导入到Java中的向量中,但是现在我想将这些数据分组,以便将类似数据与let表示相同的ID进行分组(在我的情况下为物质编号)。
这是我的相关导入代码:
public class FileChooser extends javax.swing.JFrame {
private String path ="";
public FileChooser() {
initComponents();
}
private static Vector importExcelSheet(String fileName)
{
Vector cellVectorHolder = new Vector();
try
{
Workbook workBook = WorkbookFactory.create(new FileInputStream(fileName));
Sheet sheet = workBook.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
while(rowIter.hasNext())
{
XSSFRow row = (XSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
Vector cellStoreVector=new Vector();
while(cellIter.hasNext())
{
XSSFCell cell = (XSSFCell) cellIter.next();
cellStoreVector.addElement(cell);
}
cellVectorHolder.addElement(cellStoreVector);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return cellVectorHolder;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int option = chooser.showOpenDialog(this); // parentComponent must a component like JFrame, JDialog...
if (option == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
path = selectedFile.getAbsolutePath();
jTextField1.setText(path);
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Vector dataHolder = importExcelSheet(path);
Enumeration e = dataHolder.elements(); // get all vector elements
while (e.hasMoreElements()) { // step through all vector elements
Object obj = e.nextElement();
System.out.println(obj);
}// TODO add your handling code here:
}
这会选择excel电子表格并将所有值提取到矢量并打印出来,我想知道的是,我可以在矢量中对相同的数据进行分组并输出该数据而不是整个数据。
所以我想说我有手机合约的电子表格,我想选择三星galaxy s3的所有合约而不是所有合约,我该怎么做?
答案 0 :(得分:0)
您患有Object Denial: - )
在我阅读您的代码时,您有Vector
行包含向量列的行,这是正确的吗?如果是这样,其中一列是否包含手机型号?
无论如何,你可以按照以下方式做点什么:
// TODO seriously consider something else than Vector to store the rows and columns!
Map<String,Vector> map = new HashMap<String,Vector>()
while(rowIter.hasNext())
{
boolean isFirst = false;
String phoneModel = "";
while( cellIter.hasNext() )
{
XSSFCell cell = (XSSFCell) cellIter.next();
if ( isFirst ) { phoneModel = cell.getTheTextContentOrWhatever(); isFirst = false; }
cellStoreVector.addElement(cell);
}
if ( map.get( phoneModel ) == null ) { map.put( phoneModel , new Vector() ); }
map.get( phoneModel ).add( cellStoreVector );
}
然后,地图键将成为您的手机,其值将为Vector
,其中包含该手机的行数。我不认为漂亮的代码和需求在错误处理方面有效,但你可以从那里开始工作。
干杯,