码迷,mamicode.com
首页 > 编程语言 > 详细

java导出excel不须要额外jar包

时间:2017-07-26 11:33:43      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:track   java   []   public   stack   pre   csv   stat   导出excel   

   眼下我知道的在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;
	}

}
将源代码复制后能够直接执行。

java导出excel不须要额外jar包

标签:track   java   []   public   stack   pre   csv   stat   导出excel   

原文地址:http://www.cnblogs.com/gavanwanggw/p/7238517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!