我是靠谱客的博主 纯情过客,这篇文章主要介绍Java怎么将数据写入ExcelJava怎么将数据写入Excel,现在分享给大家,希望可以做个参考。

Java怎么将数据写入Excel


上一篇是java怎么读取Excel表数据

个人把这个方法封装了WriteToExcel

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class WriteToExcel { private static XSSFWorkbook workbook; private static XSSFSheet sheet; private static XSSFRow row; private static XSSFCell cell; private static File file; //创建sheet页 public static void setSheet(String sheetName) { workbook = new XSSFWorkbook(); sheet = workbook.createSheet(sheetName); } //创建表头 public static void createHead(List<String> headList) { //创建表头,也就是第一行 row = sheet.createRow(0); for (int i = 0; i < headList.size(); i++) { cell = row.createCell(i); cell.setCellValue(headList.get(i)); } } //创建表内容 public static void createContent(List<List<String>> contentList) { //创建表内容,从第二行开始 for (int i = 0; i < contentList.size(); i++) { row = sheet.createRow(i + 1); for (int j = 0; j < contentList.get(i).size(); j++) { row.createCell(j).setCellValue(contentList.get(i).get(j)); } } } //写入文件 public static void writeToFile(String filePath){ file = new File(filePath); //将文件保存到指定的位置 try { workbook.write(new FileOutputStream(file)); System.out.println("写入成功"); workbook.close(); } catch (IOException e) { e.printStackTrace(); } } // 内容测试数据 protected static List<List<String>> getContent() { List<List<String>> contentList = new ArrayList<>(); List<String> content1 = new ArrayList<>(); content1.add("张三"); content1.add("18"); List<String> content2 = new ArrayList<>(); content2.add("李四"); content2.add("20"); contentList.add(content1); contentList.add(content2); return contentList; } public static void main(String[] args) { //表头测试数据 List<String> headList = new ArrayList<>(); headList.add("昵称"); headList.add("年龄"); List<List<String>> contentList = getContent();//内容测试数据 setSheet("WorkSheet"); //创建sheet页 createHead(headList); //设置表头 createContent(contentList); //设置内容 writeToFile("D://work.xls"); //写入文件 } }

总结

这其中还有一些设置表格的方法,但是个人认为在此处设置样式没啥太大意义,可以直接在生成的excel表里直接设置,代码设置的话不灵活,如果还是想添加样式的话可以以此为模板再从中设置一些样式方法,这与我的模板并不冲突

最后

以上就是纯情过客最近收集整理的关于Java怎么将数据写入ExcelJava怎么将数据写入Excel的全部内容,更多相关Java怎么将数据写入ExcelJava怎么将数据写入Excel内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部