首页 > 代码库 > java导出excel不需要额外jar包
java导出excel不需要额外jar包
目前我知道的在java中导出Excel可以用poi或在jsp的文件头改变输出流。下面再介绍一种就用java基础包导出的Excel。导出的格式形如:
源码如下:
package csvExcel; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CsvAction { public static void main(String[] args) { new CsvAction().exportData2CSV(); } private String fileName; public void exportData2CSV() { List<Novel> novels = getNovels(); fileName = "D:/novels.csv"; writeData2CSV(novels, fileName); System.out.println("D:/novels.csv下文件生成成功"); } private void writeData2CSV(List<Novel> novels, String fileName2) { FileWriter fw = null; try { fw = new FileWriter(fileName); // 输出标题头 // 注意列之间用","间隔,写完一行需要回车换行"\r\n" String title = "序号,小说名称,作者,出版日期\r\n"; fw.write(title); String content = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (int i = 0; i < novels.size(); i++) { Novel novel = novels.get(i); // 注意列之间用","间隔,写完一行需要回车换行"\r\n" content = (i + 1) + "," + novel.getName() + "," + novel.getAuthor() + "," + sdf.format(novel.getPublishTime()) + "\r\n"; fw.write(content); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { if (fw != null) { fw.close(); } } catch (IOException e) { e.printStackTrace(); } } } private List<Novel> getNovels() { List<Novel> novels = new ArrayList<Novel>(); Novel novel1 = new Novel("风云第一刀", "古龙", new Date()); Novel novel2 = new Novel("书剑恩仇录", "金庸", new Date()); Novel novel3 = new Novel("陆小凤传奇", "古龙", new Date()); Novel novel4 = new Novel("鹿鼎记", "金庸", new Date()); novels.add(novel1); novels.add(novel2); novels.add(novel3); novels.add(novel4); return novels; } }将源码复制后可以直接运行。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。