好的,您可以使用 Apache POI 库生成 Excel 文件。以下是一段使用 POI 库在 Java 中生成 Excel 文件并填充随机字符串的样例代码:
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelGenerator {
public static void main(String[] args) {
// Create a set to hold unique strings
Set<String> stringSet = new HashSet<>();
Random random = new Random();
// Generate 10000 unique strings
while (stringSet.size() < 10000) {
String randomString = generateRandomString(random, 10);
stringSet.add(randomString);
}
// Initialize a new workbook
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 14);
font.setBold(true);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(new XSSFColor(new java.awt.Color(160, 190, 220)));
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setFont(font);
// Create a new sheet in the workbook
Row row;
Cell cell;
int rowCount = 0;
int cellCount = 0;
int sheetCount = 0;
workbook.createSheet("Sheet " + sheetCount);
while (rowCount < 10000) {
if (cellCount == 0) {
// Create a new row for every 10 cells
row = workbook.getSheetAt(sheetCount).createRow(rowCount);
rowCount++;
} else {
row = workbook.getSheetAt(sheetCount).getRow(rowCount - 1);
}
// Create a new cell in the current row
cell = row.createCell(cellCount);
// Set the cell value to a random string from the set
cell.setCellValue(stringSet.stream().skip(rowCount + cellCount).findFirst().orElse(""));
// Apply the style to the cell
cell.setCellStyle(style);
cellCount++;
if (cellCount == 10) {
cellCount = 0;
}
if (rowCount == 1000 && cellCount == 0) {
// Create a new sheet for every 1000 rows
sheetCount++;
workbook.createSheet("Sheet " + sheetCount);
rowCount = 0;
}
}
// Save the workbook to a file
try {
FileOutputStream outputStream = new FileOutputStream(new File("output.xlsx"));
workbook.write(outputStream);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// A utility function to generate a random string of given length
private static String generateRandomString(Random random, int length) {
StringBuilder stringBuilder = new StringBuilder();
while (stringBuilder.length() < length) {
stringBuilder.append((char) (random.nextInt(26) + 'a'));
}
return stringBuilder.toString();
}
}
此代码将在项目的根目录下生成一个名为“output.xlsx”的 Excel 文件,并将其填充为 10000 个随机且不重复的字符串。
注:此代码已经包含 Apache POI 的相关库。如果您想在自己的项目中使用,请在 build.gradle 或 pom.xml 中添加以下内容:
build.gradle:
implementation 'org.apache.poi:poi-ooxml:4.1.2'
pom.xml:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
您可以根据需要自定义生成的 Excel 文件的样式、单元格格式和数据等其他特性。