简体   繁体   English

使用Apache POI写入excel文件,但FileOutput仅包含一列

[英]Using Apache POI to write excel file, but FileOutput only contains one column

I've written a code that takes in data from one input excel file and writes a new output file with the desired organization. 我编写了一个代码,该代码从一个输入的excel文件中获取数据,并使用所需的组织编写一个新的输出文件。 The problem I'm encountering is that it when I open the Java file only the column that was the latest within the for loop has data. 我遇到的问题是,当我打开Java文件时,仅for循环中最新的列具有数据。 I have tested to see if my for loop is wrong by breaking the for loop at different times. 我通过在不同的时间断开for循环来测试我的for循环是否错误。 The tests show that it does write the correct data in the correct column. 测试表明,它确实在正确的列中写入了正确的数据。 I have no idea why it chooses to erase the previous column. 我不知道为什么选择删除上一列。 Is there a line I am missing to save the cell values I had just made to keep the data on the sheet I am working on? 我是否缺少一行来保存刚将单元格值保存在正在处理的工作表上的单元格值?

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
import org.apache.poi.ss.usermodel.ConditionalFormattingRule;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ComparisonOperator;//compare two different values
import org.apache.poi.ss.usermodel.PatternFormatting;
import org.apache.poi.ss.usermodel.IndexedColors;


 import java.util.Iterator;
import java.io.*;
import javax.swing.JFileChooser;

public class Reorganizer 
{
public static void main(String[] args)
{
    /*File Chooser*/
    JFileChooser fileChooser = new JFileChooser();//lets user choose file
    int returnValue = fileChooser.showOpenDialog(null);//null bc we don't have parent classes, lets user choose through an open window

    if(returnValue == JFileChooser.APPROVE_OPTION)
    {
        try 
        {
            Workbook wb= new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));//setting the input file as a workbook
            Sheet inputSheet = wb.getSheetAt(0);//the sheet from the input file

            Workbook wb1 = new HSSFWorkbook();//creating a new workbook to later be put into the output file
            Sheet outputSheet = wb1.createSheet("Sheet 1");//creates new sheet on the output excel file

            //first need something to find cell# of the file
            Row idRow = inputSheet.getRow(0);
            int cellCounter=0;
            for(Iterator<Cell> cit = idRow.cellIterator(); cit.hasNext();)//goes down the row, until there is nothing
            {                   
                Cell cell = cit.next();
                cellCounter++;
            }
            //finds the number of rows
            int rowCounter=0;
            for(Iterator<Row> rit = inputSheet.rowIterator();rit.hasNext();)//goes down the column, until there is nothing
            {                   
                Row row = rit.next();
                rowCounter++;
            }


            //The first row of the document should be the labeling process
            //Set the row(0) and the cells(9)
            Row labelRow = outputSheet.createRow(0);
            //for loop to make 9 cells with labels
            String[] cellValues = new String[]{"Chr","Pos","Olfr","Subfamily","Cluster","OP6u","OP6d","OP27u","OP27d"};
            for(int i=0; i<=9;i++)
            {
                Cell labelCells = labelRow.createCell(i);
                if(i<=8)
                {
                     labelCells.setCellValue(cellValues[i]);
                     for(Iterator<Cell> cit = idRow.cellIterator(); cit.hasNext(); )
                        {
                            Cell cell = cit.next();
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            if(cellValues[i].equals(cell.getStringCellValue()))
                            {
                                for(int j=1;j<rowCounter;j++)
                                {
                                    int cellnum = cell.getColumnIndex();
                                    Cell inputCell = inputSheet.getRow(j).getCell(cellnum);
                                    inputCell.setCellType(Cell.CELL_TYPE_STRING);
                                    String data = inputCell.getStringCellValue();
                                    Cell outputCell = outputSheet.createRow(j).createCell(i);
                                    outputCell.setCellValue(data);
                                    System.out.println(cellnum);//tells me where the input column was from
                                    System.out.println(i);////tells me what row cell I'm writing on
                                    System.out.println(j);//tells me what row number 
                                    System.out.println(data);//tells me the data being inputed into file
//used the above prints to find out what it was doing, 
//this is the code used to write the data


                                }
                            }

                        }
                } 
                else 
                {
                     labelCells.setCellValue("");
                }

            }

        FileOutputStream output = new FileOutputStream("Reorganized.xls");
        wb1.write(output);
        output.flush();
        output.close();
        }
        catch (FileNotFoundException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


    }

}

}   

Seem like your problem is here. 好像您的问题在这里。 When you call createRow(), it will erase existing data. 调用createRow()时,它将删除现有数据。

Cell outputCell = outputSheet.createRow(j).createCell(i);

You can either pre-create all the rows before you populate data or you can call getRow() to test if the row already exists. 您可以在填充数据之前预先创建所有行,也可以调用getRow()来测试该行是否已经存在。 You need something like this: 您需要这样的东西:

Row row = outputSheet.getRow(j);
if (row == null) {
    row = outputSheet.createRow(j);
}
Cell outputCell = row.createCell(i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM