使用Apache POI在Excel中写入二维整数数组。

huangapple go评论71阅读模式
英文:

Write 2d arrays of integers on Excel using Apache POI

问题

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExportToExcel {

    public static void WriteExcel(int[][] arrayOne, int[][] arrayTwo) {
        
        String fileName = "MyExcelFile.xlsx";
        String sheetName = "5x5";
        
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(sheetName);
        
        // Header of the Excel File
        String[] header = new String[] {"col 0", "col 1", "col 2", "col 3", "col 4"};
        
        // Fill the Excel File with headers and data
        for (int rowIndex = 0; rowIndex <= arrayOne.length; rowIndex++) {
            XSSFRow row = sheet.createRow(rowIndex);
            
            for (int columnIndex = 0; columnIndex < header.length; columnIndex++) {
                XSSFCell cell = row.createCell(columnIndex);
                
                if (rowIndex == 0) {
                    // Set header values
                    cell.setCellValue(header[columnIndex]);
                } else {
                    // Set matrix values
                    int value = columnIndex < arrayOne[rowIndex - 1].length ? arrayOne[rowIndex - 1][columnIndex] : arrayTwo[rowIndex - 1][columnIndex - arrayOne[rowIndex - 1].length];
                    cell.setCellValue(value);
                }
            }
        }
        
        // Save the workbook to a file
        try {
            FileOutputStream fileOut = new FileOutputStream(fileName);
            workbook.write(fileOut);
            fileOut.close();
            workbook.close();
            System.out.println("Excel file created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        int[][] arrayOne = {
            {2, 0, 1, 3, 4},
            {0, 1, 2, 3, 4},
            {0, 2, 1, 4, 3},
            {2, 1, 0, 4, 3},
            {2, 0, 1, 3, 4}
        };

        int[][] arrayTwo = {
            {1, 1, 4, 1, 1},
            {4, 4, 0, 4, 4},
            {0, 0, 1, 0, 0},
            {2, 3, 3, 3, 3},
            {3, 2, 2, 2, 2}
        };

        WriteExcel(arrayOne, arrayTwo);
    }
}

Note: The code above is a complete Java program that exports the given matrices to an Excel file using Apache POI. Make sure you have the necessary libraries and imports set up correctly in your project.

英文:

I am trying to export 2d arrays of integers to Excel. Precisely, I need to export 2 arrays of integers of the same dimension. I previously installed the libraries for using Apache POI in Java using Eclipse IDE.

My idea is to pass as parameters for the writeExcel method 2 arrays of integers (arrayOne and arrayTwo) and get as a result an Excel file where 2 matrices were written with their respective values. For example, for the case where both matrices are from 5x5 dimension this is what I tried:

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExportToExcel {
public static void WriteExcel(int[][] arrayOne, int[][] arrayTwo) {
String fileName = &quot;MyExcelFile.xlsx&quot;;
String sheet = &quot;5x5&quot;;
XSSFWorkbook book = new XSSFWorkbook();
XSSFSheet hoja1 = book.createSheet(sheet);
// Header of the de Excel File
String[] header = new String[] {&quot;col 0&quot;, &quot;col 1&quot;, &quot;col 2&quot;, &quot;col 3&quot;, &quot;col 4&quot;}; 
// Fill the Excel File
for (int i = 0; i &lt;= ruta.length; i++) {
XSSFRow row = hoja1.createRow(i);
for (int j = 0; j &lt; header.length; j++) {
if (i == 0) {
XSSFCell cell = row.createCell(j);
cell.setCellValue(header[j]);
}
else {
XSSFCell cell = row.createCell(j);
// some code here??
}
}
}
}
}

Clearly, in the previous code are missing parts that I don't know how to include. Thus, if I pass as a parameters to the method the following 2 matrices:

arrayOne: [[2, 0, 1, 3, 4], [0, 1, 2, 3, 4], [0, 2, 1, 4, 3], [2, 1, 0, 4, 3], [2, 0, 1, 3, 4]]
arrayTwo: [[1, 1, 4, 1, 1], [4, 4, 0, 4, 4], [0, 0, 1, 0, 0], [2, 3, 3, 3, 3], [3, 2, 2, 2, 2]]

The expected result in Excel must be something like:

使用Apache POI在Excel中写入二维整数数组。

Thanks in advance if anyone can help me with this question.

答案1

得分: 1

你应该遍历整个 Excel 工作表,然后检查是否在所需单元格中,写入相应的值。

一种方法是使用 CellReference。通过它,你可以引用一个单元格,然后获取其行/列索引并在其上写入。

例如:

CellReference A1 = new CellReference("A1");

int row = cr.getRow();
int col = cr.getCol();

现在你已经得到了 A1 单元格的行/列索引,你可以像这样在这个位置写入:

Row row1 = ((sheet.getRow(row) == null) ? sheet.createRow(row) : sheet.getRow(row));

通过上面的代码,你检查行是否存在,如果不存在,就创建一行。

Cell cell;
if (row1.getCell(col) == null) {
    cell = row1.createCell(col);
} else {
    cell = row1.getCell(col);
}

通过上面的代码,你检查特定行上的特定单元格是否为空,如果为空,则创建一个新的单元格,否则使用其引用。

现在,你已经准备好在 A1 单元格上写入数据。只需执行以下操作:

cell.setCellValue("arrayOne");

所以现在,只需使用表示工作表中行/列索引的行和列,然后在所选单元格中写入数据。

例如,通过执行 col+=1,你可以获得 B1,通过在循环中重复上述代码,并在循环内部每次增加列和/或行索引,你可以按照希望的方式在工作表中编写数组。

如有需要,欢迎随时向我询问额外的澄清。

英文:

You should iterate through the whole excel sheet and then check if you are in the desired cell, write the appropriate value.

One way to do this, is with CellReference . With that you can reference to a cell and then take its row/col index an write on it.

For example:

CellReference A1 = new CellReference(&quot;A1&quot;);
int row = cr.getRow();
int col = cr.getCol();

Now you got the index for row/col of A1 and you can write on this position like this:

Row row1 = ((sheet.getRow(row)==null) ? sheet.createRow(row) : sheet.getRow(row));

With the line above you check if the row exists, and if not, then you create one.

Cell cell;
if (row1.getCell(col) == null) {
cell = row1.createCell(col);
} else {
cell = row1.getCell(col);
}

With the above, you check the specific cell on the specific row if its empty, and if it is then you create a new one, else you the its reference.

Now, you are ready to write on A1 cell. Simply do:

cell.SetCellValue(&quot;arrayOne&quot;);

So now, just use row and col that represent the index for row/col in your sheet and write in the cells of your choice.

For example by doing col+=1 you getting B1 and by repeating the above code in a for loop and increment every time the col and/or row index inside your loop, you can write the arrays in the way you want on your sheet.

Please feel free to ask me for extra clarification.

huangapple
  • 本文由 发表于 2020年10月23日 22:48:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64502237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定