简体   繁体   English

如何使用Java在工作簿中创建Excel工作表?

[英]how to create excel sheet in workbook using java?

I have to find the example string in excel sheet as I have to change it using java. 我必须在excel工作表中找到示例字符串,因为我必须使用java对其进行更改。 I did it easily. 我很容易做到。 But the problem comes when I have to do it same for specific times and each time I have to copy the data into new sheet. 但是问题出在我必须在特定时间执行相同操作并且每次必须将数据复制到新工作表中时。 So if I have to do it for 5 times then there should be 5 worksheet in my excel workbok. 因此,如果我必须做5次,那么我的excel工作簿中应该有5个工作表。

Here is my code. 这是我的代码。

int a=1;            
String match="Keval Dalsaniya";    
String[] name={"Ankit","Keval","Varun","Dhaval","Nirav"}; 
int i;
try {
FileInputStream file = new FileInputStream(new File("D:\\Ankit\\Data\\data.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);

        for(i=0;a<=name.length;i++,a++)
        {
            Cell cell = null;
            cell = sheet.getRow(0).getCell(4);
            workbook.createSheet(name[i]);          
            if(cell.getStringCellValue().equals(match))
                cell.setCellValue(name[i]);
            else
                JOptionPane.showMessageDialog(null, "No match found.");

            System.out.println(name[i]);

        } 
            file.close();

            FileOutputStream outFile =new FileOutputStream(new File("D:\\Ankit\\Data\\update.xlsx"));
            workbook.write(outFile);
            outFile.close();


    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }

Use 采用

XSSFSheet newSheet = workbook.createSheet();

and put edited String in the newly created sheet. 并将已编辑的String放在新创建的工作表中。

Hope this helps. 希望这可以帮助。

Edit: 编辑:

You are creating a new sheet but not using it. 您正在创建一个新工作表,但没有使用它。
Try the following. 请尝试以下方法。

XSSFSheet sheet = workbook.getSheetAt(0);

for (i = 0; a <= name.length; i++,a++)
{
    Cell cell = null;
    cell = sheet.getRow(0).getCell(4);
    XSSFSheet newSheet = workbook.createSheet(name[i]);
    // createRow and createCell should come to rescue here.
    Cell cellInNewSheet = newSheet.getRow(0).getCell(4);          
    if (cell.getStringCellValue().equals(match)) {
        cellInNewSheet.setCellValue(name[i]);
    }
    else {
        JOptionPane.showMessageDialog(null, "No match found.");
    }
    System.out.println(name[i]);
}

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

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