使用for循环写入Excel文件中的单元格,删除上一列

时间:2015-10-01 04:40:53

标签: java excel apache-poi

我试图编写一个代码,在输入的Excel文件中找到某个列,并在输出的excel文件中重新组织它。我已经完成了for循环并且它有效。但是,当我尝试为下一个条件设置类似的for循环时,它会删除之前在if语句中写入的列。我似乎无法弄清楚为什么会这样。 我有程序打印了cellnum,j,i和数据,它似乎知道它应该写入数据的位置,但它仍然只在输出文件中打印一列数据。

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","OR","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);
                                    System.out.println(i);
                                    System.out.println(j);
                                    System.out.println(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();
        }


    }

}

}

1 个答案:

答案 0 :(得分:0)

在不编译代码的情况下,看起来在写入FileOutputStream输出时可能存在错误。尝试在关闭流之前运行flush()。

您的代码正在执行此操作:

FileOutputStream output = new FileOutputStream("ChrTestExcel.xls");
wb1.write(output);
output.close();

请改为尝试:

FileOutputStream output = new FileOutputStream("ChrTestExcel.xls");
wb1.write(output);
output.flush();
output.close();

走完代码后,似乎需要进行一些清理工作。首先,您可以更简洁地使用您的代码。第一个循环可以缩短:

现有的循环

for(int i=0; i<=9;i++)
        {
            Cell labelCells = labelRow.createCell(i);
            //if statements that make the labels
            if(i==0)
            {
                labelCells.setCellValue("Chr");
            }
            else if(i==1)
            {
     ...

建议重构简洁

String[] cellValues = new String[]{"Chr","Pos","OR","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]);
    } else {
         labelCells.setCellValue("");
    }
    //do something with the cell you just created! 
}

第二部分是对您正在创建的单元格实际执行某些操作(请参阅前面的代码示例)。一旦该循环从i == 0变为i == 1,labelCells的值就会丢失(范围错误)。不知何故,你必须增加单元格的位置,将它添加到一行等等。