easyexcel 随机生成电话号码
时间: 2023-11-22 20:49:13 浏览: 131
以下是使用EasyExcel随机生成电话号码的示例代码:
```java
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PhoneGenerator {
public static void main(String[] args) {
// 生成10个电话号码
List<Phone> phoneList = generatePhoneList(10);
// 写入Excel文件
String fileName = "phone.xlsx";
ExcelWriterBuilder writerBuilder = EasyExcel.write(fileName, Phone.class);
ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet();
WriteSheet writeSheet = sheetBuilder.build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, null);
EasyExcel.write(fileName, Phone.class).registerWriteHandler(horizontalCellStyleStrategy).fill(phoneList, fillConfig, writeSheet).finish();
System.out.println("Excel文件已生成:" + fileName);
}
/**
* 生成指定数量的电话号码
*
* @param count 生成数量
* @return 电话号码列表
*/
private static List<Phone> generatePhoneList(int count) {
List<Phone> phoneList = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < count; i++) {
StringBuilder sb = new StringBuilder();
// 生成电话号码前缀
sb.append("1");
for (int j = 0; j < 2; j++) {
sb.append(random.nextInt(10));
}
sb.append("-");
// 生成电话号码后缀
for (int j = 0; j < 8; j++) {
sb.append(random.nextInt(10));
}
phoneList.add(new Phone(sb.toString()));
}
return phoneList;
}
/**
* 电话号码实体类
*/
public static class Phone {
@ExcelProperty("电话号码")
private String phone;
public Phone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
}
```
阅读全文