批量生成随机字符串并保存到excel

时间:2025-04-30 18:04:19

需要导入jxl.jar,commons-lang-2.6.jar

链接:https://pan.baidu.com/s/1NPPh24XWxkka68x2JQYlYA
提取码:jvj3

链接:https://pan.baidu.com/s/1d68GzCbXFIx41uPiWZpAkg
提取码:z2az

package exceldemo;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random; import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test; import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException; /**
*
* @author csh
* 批量创建随机字符串并保存到excel
*/ public class JxlWriteDemo { public static void main(String[] args) throws IOException, WriteException {
Random r = new Random();
Date date = new Date();
// String curdate = date.toString();
DateFormat df6 = new SimpleDateFormat("yyMMddhhmmss");
String formatdate = df6.format(date);
File fileDir=new File("D:\\exceldata");
if(!fileDir.exists()){
fileDir.mkdir();
}
File xlsFile = new File("D:\\exceldata\\jxl" + formatdate + ".xls"); // 创建一个工作簿
WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
// 创建一个工作表
WritableSheet sheet = workbook.createSheet("sheet1", 0);
// 设置titles
String[] titles = { "卡号" };
// 设置单元格
Label label = null;
// 给第一行设置列名
for (int i = 0; i < titles.length; i++) {
// x,y,第一行的列名
Label lable = new Label(i, 0, titles[i]);
// 添加单元格
sheet.addCell(lable); } for (int row = 1; row < 3000; row++) {
for (int col = 0; col < 1; col++) {
// //获取当前时间的时间戳
// long currentTimeMillis = System.currentTimeMillis();
// 生成三位随机整数
int rundomInt = r.nextInt(999);
// 如果不足三位前面补0
String vipCode = String.format("%03d", rundomInt); // 随机生成字符串
String filename = RandomStringUtils.randomAlphanumeric(10);
// 随机字符串+日期,生成激活码
String code = filename + formatdate;
// 向工作表中添加数据
sheet.addCell(new Label(col, row, "VIP" + filename + vipCode));
}
}
workbook.write();
workbook.close(); }
}