本质:输出流的应用
输出到txt步骤:
1.组装文件数据
2.写入txt,生成文件(封装工具类)
/**
*写入txt工具类
* @param result 文件数据
*/
private void writeTxt(List<String> result){
BufferedWriter out =null;
String filePath="D:\\study";
if (CollectionsUtils.isNotEmpty(result)){
try {
File pathFile = new File(filePath);
if (!pathFile.exists()){
pathFile.mkdirs();//创建多层目录
}
String s = filePath + File.separator + "临时文件.txt";
File file=new File(s);
if (!file.exists()){
file.createNewFile();
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
// 创建标题行并换行
out.write("姓名,年龄,性别,工作");
out.newLine();
for (String item:result) {
out.write(item);
out.newLine();
}
} catch (IOException e) {
log.error("转存文件失败",e);
}finally {
if (out!=null){
try {
out.flush();
out.close();
} catch (IOException e) {
log.error("关闭流失败",e);
}
}
}
}
}
测试一下:
输出到excel步骤:
1.准备excel列对应的实体类
2.创建数据
3.调用生成excel的方法,返回bytes数组
4.利用文件输出流,输出到指定位置
private static byte[] createExcel(String[] keys, String[] columns,List<DacuCase> results){
ByteArrayOutputStream os=new ByteArrayOutputStream();
try {
Workbook wb = new SXSSFWorkbook(100);
Sheet sheet =wb.createSheet("sheet1");
CellStyle cs=wb.createCellStyle();
// 初始化excel文件格式
ExcelUtil.initExcleSyleAndHeader(wb,sheet,columns,keys,cs,cs);
// 准备数据
List<Map<String,Object>> listMap = new ArrayList<>();
Map<String,Object> map = new HashMap<>();
map.put("sheetName","sheet1");
listMap.add(map);
for (DacuCase item:results){
Map<String,Object> map1 = new HashMap<>();
map1.put("manager",item.getManager());
map1.put("address",item.getAddress());
map1.put("outterAppId",item.getOutterAppId());
listMap.add(map1);
}
// 数据写入sheet
ExcelUtil.createContentRows(0,sheet,listMap,keys,cs);
wb.write(os);
}catch (Exception e){
log.error("导出到excel异常",e);
}finally {
if (os!=null){
try {
os.close();
} catch (IOException e) {
log.error("关闭流失败",e);
}
}
}
return os.toByteArray();
}
private static void writeEcxel(){
String [] keys ={"manager","address","outterAppId"};
String [] columns ={"负责人","地区","客户姓名"};
String fileName ="临时文件.xlsx";
List<DacuCase> results = new ArrayList<>();
// 造数据
DacuCase d1 = new DacuCase();
d1.setManager("张三");
d1.setAddress("三亚");
d1.setOutterAppId("38947951");
DacuCase d2 = new DacuCase();
d2.setManager("李四");
d2.setAddress("大理");
d2.setOutterAppId("46347423");
results.add(d1);
results.add(d2);
//创建文件输出流 并输出
FileOutputStream outputStream=null;
byte[] bytes = createExcel(keys, columns, results);
try{
File file = new File("D:\\study");
if (!file.exists()){
file.mkdirs();
}
String allPath = file + File.separator + fileName;
outputStream = new FileOutputStream(allPath);
File filePath = new File(allPath);
if (!filePath.exists()){
filePath.createNewFile();
}
outputStream.write(bytes);
} catch (IOException e) {
log.error("创建文件异常",e);
} finally {
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
log.error("关闭流失败",e);
}
}
}
}
测试下:
导出成功~
这里为了方便,都是造的简单数据,而实际开发中,数据都是我们从数据库中查询的~