整个项目中导出数据到.Excel的源码
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import Vo.SellAnimal;
public class FileUtils {
public static final String SEPARATE_FIELD = ",";// 逗号分隔符
public static final String SEPARATE_LINE = "\r\n";// 行分隔符
public static void saveAniaml(SellAnimal animal) {
Date data = new Date(); // 获取系统时间
SimpleDateFormat fmort = new SimpleDateFormat("yyyyMMdd");// 注时间格式
String time = "销售记录" + fmort.format(data) + ".csv";
InputStream in = null; // 输入流,读取文件的内容
try {
in = new FileInputStream(time);//向上转型
if (in != null) {
in.close();
creatfile(time, true, animal);// 在已有文件的后面接着写
}
} catch (FileNotFoundException e) {
creatfile(time, false, animal);// 创建新的文件
} catch (IOException e) {
e.printStackTrace();
}
}
public static void creatfile(String time, boolean object, SellAnimal animal) {
// TODO Auto-generated method stub
BufferedOutputStream out = null;// 字节缓冲流
StringBuffer str = new StringBuffer();
try {
if (object) {
out = new BufferedOutputStream(new FileOutputStream(time, true));
} else {
out = new BufferedOutputStream(new FileOutputStream(time));
String[] filesort = { "宠物名称", "宠物编号", "宠物品种", "宠物数量", "宠物单价(/元)", "总价" };
for (String fieldKey : filesort) {
str.append(fieldKey).append(SEPARATE_FIELD);
}
}
str.append(SEPARATE_LINE);
str.append(animal.getName()).append(SEPARATE_FIELD);
str.append(animal.getNum()).append(SEPARATE_FIELD);
str.append(animal.getPin()).append(SEPARATE_FIELD);
str.append(animal.getShu()).append(SEPARATE_FIELD);
str.append(animal.getPrice()).append(SEPARATE_FIELD);
str.append(animal.getMoney()).append(SEPARATE_FIELD);
String str1 = str.toString();
byte[] shu = str1.getBytes();
for (int i = 0; i < shu.length; i++) {
out.write(shu[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}