java代码生成1万条6个特征和一个结果的数据写入xlsx
时间: 2024-03-26 16:39:54 浏览: 16
好的,下面是生成1万条数据并写入xlsx的java代码:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class GenerateData {
private static final int ROW_COUNT = 10000; // 生成数据的行数
private static final int FEATURE_COUNT = 6; // 特征的数量
private static final int RESULT_INDEX = FEATURE_COUNT; // 结果所在列的索引
public static void main(String[] args) {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("data");
Random random = new Random();
// 写入表头
Row headerRow = sheet.createRow(0);
for (int i = 0; i < FEATURE_COUNT; i++) {
Cell headerCell = headerRow.createCell(i);
headerCell.setCellValue("feature" + (i + 1));
}
Cell headerCell = headerRow.createCell(RESULT_INDEX);
headerCell.setCellValue("result");
// 写入数据
for (int i = 1; i <= ROW_COUNT; i++) {
Row row = sheet.createRow(i);
for (int j = 0; j < FEATURE_COUNT; j++) {
Cell cell = row.createCell(j);
cell.setCellValue(random.nextDouble());
}
Cell cell = row.createCell(RESULT_INDEX);
cell.setCellValue(random.nextInt(2));
}
// 输出xlsx文件
try {
FileOutputStream outputStream = new FileOutputStream(new File("data.xlsx"));
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("数据已生成并写入data.xlsx文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码使用了Apache POI库,可以通过Maven添加以下依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
运行该代码后,会在当前目录下生成一个名为data.xlsx的文件,其中包含了1万条随机生成的数据。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)