java创建excel并向其中追加数据
作者:互联网
一. 通过POI实现向excel中追加数据
我这次需要把抓取数据的结果以追加的方式添加到excel中。因为数据中的内容字段值会有一些不确定的符号(比如常见的逗号),因此不能通过RandomAccessFile类直接见一个".csv"结尾的文件,让系统自动以“,”分割。这里使用了org.apache.poi中的一些类来完成此功能。
-
引用版本
-
初始化excel文件
private void initExcel() throws Exception{ if (!FileUtil.exist(file.getParent())) { FileUtil.mkdir(file.getParent()); } //TEMP_PATH路径下为提前建好放置的execl文件,复制文件到输出目录 FileUtil.copy(TEMP_PATH,GoogleNews.FILE_OUT_PATH ,false); //打开文件 File file = new File(GoogleNews.FILE_OUT_PATH); FileInputStream fs=new FileInputStream(file); //获取d://test.xls // POIFSFileSystem ps=new POIFSFileSystem(fs); //使用POI提供的方法得到excel的信息 XSSFWorkbook wb=new XSSFWorkbook(fs); XSSFSheet sheet = wb.getSheetAt(0);//获取到工作表,因为一个excel可能有多个工作表 XSSFRow row = sheet.getRow(0);//获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值 // System.out.println(sheet.getLastRowNum()+" "+row.getLastCellNum()); //分别得到最后一行的行号,和一条记录的最后一个单元格 FileOutputStream out=new FileOutputStream(file); //向d://test.xls中写数据 row=sheet.createRow((short)(sheet.getLastRowNum())); //在现有行号后追加数据 //title, googleLink, pubdate, source, content, contentCN, tag row.createCell(0).setCellValue("title(标题)"); //设置第一个(从0开始)单元格的数据 row.createCell(1).setCellValue("googleLink(文章链接)"); //设置第二个(从0开始)单元格的数据 row.createCell(2).setCellValue("pubdate(发布时间)"); row.createCell(3).setCellValue("source(媒体)"); row.createCell(4).setCellValue("content(内容)"); row.createCell(5).setCellValue("contentCN(译文)"); row.createCell(6).setCellValue("tag(关键词)"); out.flush(); wb.write(out); out.close(); }
-
向excel表中追加数据
private void writeNews(String title, String googleLink, String pubdate, String source,String tag) { try { //抽取url网页中的内容,content内容太短的不入库 String content = ContentExtractor.getContentByUrl(googleLink); if (StringUtils.length(content) < 300) { return; } FileInputStream fs=new FileInputStream(FILE_OUT_PATH); XSSFWorkbook wb=new XSSFWorkbook(fs); XSSFSheet sheet = wb.getSheetAt(0);//获取到工作表,因为一个excel可能有多个工作表 FileOutputStream out=new FileOutputStream(FILE_OUT_PATH); //向d://test.xls中写数据 //在现有行号后追加数据 XSSFRow row=sheet.createRow((short)(sheet.getLastRowNum()+1)); row.createCell(0).setCellValue(title); //设置第一个(从0开始)单元格的数据 row.createCell(1).setCellValue(googleLink); //设置第二个(从0开始)单元格的数据 row.createCell(2).setCellValue(pubdate); row.createCell(3).setCellValue(source); row.createCell(4).setCellValue(content); row.createCell(5).setCellValue(contentCN); row.createCell(6).setCellValue(tag); out.flush(); wb.write(out); out.close(); } catch (Throwable e) { log.error("saveNews方法发生错误", e); } }
二.通过RandomAccessFile类追加数据
对于数据内容比较简单的数据,可以通过RandomAccessFile类直接指定“.csv"文件,配合系统自带的分隔符(默认逗号)来往csv文件中追加数据
// 简单读取 (同步读取)
public static void simpleRead() {
// 读取 excel 表格的路径
String readPath = "C:\\Users\\user\\Desktop\\11.xlsx";
try {
// sheetNo --> 读取哪一个 表单
// headLineMun --> 从哪一行开始读取( 不包括定义的这一行,比如 headLineMun为2 ,那么取出来的数据是从 第三行的数据开始读取 )
// clazz --> 将读取的数据,转化成对应的实体,需要 extends BaseRowModel
Sheet sheet = new Sheet(1, 1, ExcelModel.class);
// 这里 取出来的是 ExcelModel实体 的集合
List<Object> readList = EasyExcelFactory.read(new FileInputStream(readPath), sheet);
// 存 ExcelMode 实体的 集合
List<ExcelModel> list = new ArrayList<ExcelModel>();
for (Object obj : readList) {
list.add((ExcelModel) obj);
}
/* Map<String, String> myMap = new HashMap<>();
list.forEach( e -> myMap.put(e.getNumAllocate() + "@@" + e.getNumStart(), e.getNumEnd()));*/
// 取出数据
StringBuilder str = new StringBuilder();
str.append("{");
String link = "";
String[] headArr = new String[]{"NUM", "NUM_ALLOCATEE_OR_ASSIGNEE"};
Map<String, List<ExcelModel>> collect = list.stream().collect(Collectors.groupingBy(ExcelModel::getNumAllocate));
//String s = "263 Mobile Communications (HongKong) Limited 263 移动通信(香港)有限公司";
for (String s : collect.keySet()) {
RandomAccessFile randomFile = null;
String fileName = "E:\\111\\" + s + ".csv";
// 打开一个随机访问文件流,按读写方式
try {
randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
if (randomFile.length()==0) {
randomFile.writeBytes(String.join(",", headArr));
randomFile.writeBytes("\r\n");
}
// 将写文件指针移到文件尾。
long fileLength = randomFile.length();
randomFile.seek(fileLength);
List<ExcelModel> excelModels = collect.get(s);
for (ExcelModel e : excelModels) {
for (Long i = e.getNumStart(); i <= e.getNumEnd();i++) {
randomFile.writeBytes(i + "," + s);
randomFile.writeBytes("\r\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
for (ExcelModel mode : list) { str.append(link).append("\""+mode.getNumStart()+"\":").append("\""+mode.getNumEnd()+"\":").append("\""+mode.getNumAllocate()+"\"");;
link= ",";
}
str.append("};");
System.out.println(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
标签:java,String,excel,createCell,追加,new,setCellValue,row 来源: https://www.cnblogs.com/ayueC/p/13984727.html