下载:
注意点:
File file=new File(filePath);//确定下载的位置
if(!file.exists()){ //这个的作用是:当没有父目录存在的时候,会自己创建,没有这个判断,父目录的自己手动创建
file.createNewFile();
}
知识点:这里用到output
FileOutputStream(输出流):主要用于往自定文件中输出
eg:
FileOutputStream fileout=new FileOutputStream(file);//file是指定的文件
这里是个简单的例子:
txt文件
String path="D:\\down";//下载地址
String fileName="test1.txt"; //文件名以及类型
String content="欢迎来到我的世界";//内容
//开始下载的程序
String filePath=path+File.separator+fileName;//路径
try{
File file=new File(filePath);//确定下载的位置
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fileout=new FileOutputStream(file);
byte[] con=content.getBytes();//把内容写入到con中
fileout.write(con); //写入
fileout.flush();
fileout.close();
}catch (Exception e){
e.printStackTrace();
}
方法1:是通过直接复制的方法:
主要语法:FileUtils.copyFile(A,B);:把文件A,复制到文件B下面(只能在同一个文件夹下面)
FileUtils.copyFileToDirectory(A,B):把文件A复制指定的文件夹中,不能控制命名
具体:
String pathA="A文件的绝对路径",
String pathB="B文件的绝对路径"
File A=new File(pathA);
File B=new File(pathB);
FileUtils.copyFile(A,B); 同意文件夹下
FileUtils.copyFileToDirectory(A,B) 指定文件夹下
优点:便于文件备份
缺点:文件名控制不了
方法2:
思路:读出源文件的流,直接写入另一个文件中
做法:
String path1="D:\\workspace\\work\\***\\44816b42cda36b07756c7.doc";
File source=new File(path1);
FileInputStream fileInputStream=new FileInputStream(source);
byte[] buffer = new byte[1024];
int len=-1;
while((len = fileInputStream.read(buffer)) != -1){
String str = new String(buffer,0,len);
System.out.println(str);
}
String savePath1="D:\\workspace\\work\\file";
String saveFilePath=savePath1+File.separator+fileName;
//生成一个新的文件
File file =new File(saveFilePath);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fileOutputStream=new FileOutputStream(file);
byte[] bytes = buffer;
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
修改之后:
缺点:写出的文件会乱码
方法3:下载网络文件
做法:
//下载的位置
//allUrl是quan
String savePath1="D:\\workspace\\work\\file";
String saveFilePath=savePath1+File.separator+fileName;
File file =new File(saveFilePath);
if(file.exists()){
file.delete();
}
int bytesum = 0;
int byteread = 0;
URL urlMine= new URL(allUrl);
URLConnection conn=urlMine.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(saveFilePath);
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
用http连接来下载文件
try{
//path就是http连接
URL url=new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
InputStream inputStream = conn.getInputStream();
String savePath="C:\\Users\\jrq\\Downloads\\"+fileName; //文件下载路径
File file=new File(savePath); //在指定位置生成文件
if(!file.exists()){ //如果不存在,创建
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file); //打开写入的流,准备写入
byte[] buffer = new byte[1024]; //声明一个byte,读取url里面的字符流
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
byte[] getData =bos.toByteArray();
fos.write(getData); //写入读取的流
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
bos.close();
}catch (Exception e){
}
按照模板下载excel 后缀是.xlsx
注意:后缀是.xlsx 用XSSFWorkbook
后缀是.xls 用HSSFWorkbook
跟excel的版本有关系
代码开始:
public ResponseEntity<byte[]> deriveStudentContent(HttpServletRequest request, HttpServletResponse response,String teacherTaskId, String taskStatus, String path) {
//开始写入
ServletContext servletContext = request.getServletContext();
String realPath= servletContext.getRealPath("/"+path);//得到文件所在位置
String excelName=alTeacherTaskVO.getEnginTaskTitle();
JSONArray jsonArray= JSONArray.parseArray(JSON.toJSONString(alTeacherTaskVO.getStudentTaskList()));
XSSFWorkbook wb=null;
try{
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(StringUtils.isNotBlank(realPath)){
wb=new XSSFWorkbook(new FileInputStream(new File(realPath)));
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
XSSFSheet sheet = wb.getSheetAt(0);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
XSSFRow row = null;
//第四步,创建单元格,并设置值表头 设置表头居中
XSSFCellStyle cellstyle = wb.createCellStyle();
cellstyle.setAlignment(HorizontalAlignment.CENTER);
/* //声明列对象
XSSFCell cell = null;*/
//创建内容
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
row = sheet.createRow(i + 1);
if(jsonObject.size()>0){
String studentName=jsonObject.getString("studentName"); //学生姓名
String statusName=null; //完成状态
if("0".equals(jsonObject.getString("status"))){ //0:
statusName="未开始";
}
if("1".equals(jsonObject.getString("status"))){ //0:
statusName="未完成";
}
if("2".equals(jsonObject.getString("status"))){ //0:
if("1".equals(jsonObject.getString("isDelay"))){
statusName="已完成(延迟)";
}else{
statusName="已完成";
}
}
if("3".equals(jsonObject.getString("status"))){ //0:
if("1".equals(jsonObject.getString("isDelay"))){
statusName="标准完成(延迟)";
}else{
statusName="标准完成";
}
}
String correctnessRate=jsonObject.getString("correctnessRate")+"%";//正确率
String useTime=jsonObject.getString("useTime");//用时
String finishTime="-";
SimpleDateFormat s= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(jsonObject.getLong("finishTime")!=null){
Date date=new Date(jsonObject.getLong("finishTime"));
finishTime=s.format(date);
}
XSSFCell cell0 = row.createCell(0);
cell0.setCellStyle(cellstyle);
cell0.setCellValue(i + 1);
XSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(cellstyle);
cell1.setCellValue(studentName);
XSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(cellstyle);
cell2.setCellValue(statusName);
XSSFCell cell3 = row.createCell(3);
cell3.setCellStyle(cellstyle);
cell3.setCellValue(correctnessRate);
XSSFCell cell4 = row.createCell(4);
cell4.setCellStyle(cellstyle);
cell4.setCellValue(useTime);
XSSFCell cell5 = row.createCell(5);
cell5.setCellStyle(cellstyle);
cell5.setCellValue(finishTime);
/*row.createCell(0).setCellValue(i + 1);
row.createCell(1).setCellValue(studentName);
row.createCell(2).setCellValue(statusName);
row.createCell(3).setCellValue(correctnessRate);
row.createCell(4).setCellValue(useTime);
row.createCell(5).setCellValue(finishTime);*/
}
}
//下载 **重点**
ByteArrayOutputStream output=new ByteArrayOutputStream();
wb.write(output);// 将数据写出去
InputStream inputStream1 = new ByteArrayInputStream(output.toByteArray());
byte[] body=null;
body=new byte[inputStream1.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
inputStream1.read(body);//读入到输入流里面
excelName=new String(excelName.getBytes("gbk"),"iso8859-1");//防止中文乱码
HttpHeaders headers=new HttpHeaders();//设置响应头
headers.add("Content-Disposition", "attachment;filename="+excelName+".xlsx");
HttpStatus statusCode = HttpStatus.OK;//设置响应吗
responseE=new ResponseEntity<byte[]>(body, headers, statusCode);
}
}catch (Exception e){
e.printStackTrace();
}
return responseE;
}
最新的一版下载导出
//数据统计导出
public static void exportdataDJSchool(HttpServletResponse response,HttpServletRequest request,List<Map<String,Object>> resultList,String isform,String path) {
try {
//os = response.getOutputStream(); // 输出流
//创建一个文件夹
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filePathPack=path+ "dataDJ" + File.separator;
String filePackName="dataTJ_"+sdf.format(new Date());
File file=new File(filePathPack+filePackName);
file.mkdirs();//创建父目录
//文件夹创建完毕
if(resultList.size()>0){
for(Map<String,Object> resultMap:resultList){
OutputStream os = null;//文件流
String name=resultMap.get("name").toString();
String filePath=file.getPath()+File.separator+name+"数据统计.xlsx";
/*File areaFile=new File(file.getPath()+File.separator+fileName);
if(!areaFile.exists()) {
areaFile.createNewFile();
}
FileInputStream is = new FileInputStream(areaFile);
XSSFWorkbook fs=new XSSFWorkbook(is);
SXSSFWorkbook wb = new SXSSFWorkbook(fs);*/
SXSSFWorkbook wb = new SXSSFWorkbook();
CellStyle titleStyle=wb.createCellStyle(); //表头格式
titleStyle.setBorderBottom(CellStyle.BORDER_THIN);
titleStyle.setBorderTop(CellStyle.BORDER_THIN);
titleStyle.setBorderLeft(CellStyle.BORDER_THIN);
titleStyle.setBorderRight(CellStyle.BORDER_THIN);
titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
Font font = wb.createFont();
font.setFontName("宋体");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
titleStyle.setFont(font);
CellStyle CellStyle=wb.createCellStyle();//内容格式
CellStyle.setAlignment(CellStyle.ALIGN_CENTER);
CellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
if("no".equals(isform)){ //不安表单
String[] titleList=(String[])resultMap.get("title");
List<Map<String,Object>> dataList=(List<Map<String,Object>>)resultMap.get("dataList");
Sheet sheet = wb.createSheet();
int excelRow = 0;
Row titleRow0 = (Row) sheet.createRow(0);
Row titleRow1 = null;
//设置表头:
int startCell=0;
for(String tt:titleList){
CellRangeAddress cra=new CellRangeAddress(0,1,startCell,startCell);
//sheet.addMergedRegion(cra);
Cell cell1 = titleRow0.createCell(startCell);
cell1.setCellValue(tt);
setRegionStyle(sheet,cra,titleStyle);
startCell=startCell+1;
}
//设置表头结束
//塞入数据开始
int cellnum=0;
if(dataList.size()>0){
for(int i=0;i<dataList.size();i++){
cellnum=0;
titleRow1 = sheet.createRow(i + 1);
//塞入序号
Cell cell1 = titleRow1.createCell(0);
cell1.setCellValue(String.valueOf(i+1));
cell1.setCellStyle(CellStyle);
Map<String,Object> map=dataList.get(i);
List<String>list=queryKey("noform");
if(list.size()>0){
for(String key:list){
cellnum=cellnum+1;
String value=map.get(key)==null ? "" : map.get(key).toString();
cell1 = titleRow1.createCell(cellnum);
cell1.setCellValue(value);
cell1.setCellStyle(CellStyle);
}
}
}
}
//塞入数据完毕
}else{//按表单
List<Map<String,Object>> formLabelList=(List<Map<String,Object>>)resultMap.get("dataList");
if(formLabelList.size()>0){
for(Map<String,Object> formLabelmap:formLabelList){ //这里是sheet名,title,数据
String[] titleList=(String[])formLabelmap.get("title"); //title
String sheetName=formLabelmap.get("formName").toString(); //sheet名
String tableName=formLabelmap.get("tableName").toString(); //表名
List<Map<String,Object>> dataList=(List<Map<String,Object>>)formLabelmap.get("dataList"); //数据
//创建sheet
Sheet sheet = wb.createSheet(sheetName);
int excelRow = 0;
Row titleRow0 = (Row) sheet.createRow(0);
Row titleRow1 = null;
//设置表头:
int startCell=0;
for(String tt:titleList){
CellRangeAddress cra=new CellRangeAddress(0,1,startCell,startCell);
//sheet.addMergedRegion(cra);
Cell cell1 = titleRow0.createCell(startCell);
cell1.setCellValue(tt);
setRegionStyle(sheet,cra,titleStyle);
startCell=startCell+1;
}
//设置表头结束
//塞入数据开始
int cellnum=0;
if(dataList.size()>0){
for(int i=0;i<dataList.size();i++){
cellnum=0;
titleRow1 = sheet.createRow(i + 1);
//塞入序号
Cell cell1 = titleRow1.createCell(0);
cell1.setCellValue(String.valueOf(i + 1));
cell1.setCellStyle(CellStyle);
Map<String,Object> map=dataList.get(i);
List<String>list=queryKey(tableName);
if(list.size()>0){
for(String key:list){
cellnum=cellnum+1;
String value=map.get(key)==null ? "" : map.get(key).toString();
cell1 = titleRow1.createCell(cellnum);
cell1.setCellValue(value);
cell1.setCellStyle(CellStyle);
}
}
}
}
//塞入数据完毕
}
}
}
os = new FileOutputStream(filePath);
wb.write(os);
}
//创建zip文件
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(path+ "excel" + File.separator+"daochu.zip");
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(path+ "excel" + File.separator+"daochu.zip"); //读入原文件 把东西读进内存中
FileOutputStream fs = new FileOutputStream(filePathPack+filePackName+".zip"); //从内存中把东西写进文件中
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
fs.close(); //必须关闭写的流,不然程序运行结束之后,还是不能打开
inStream.close(); //关闭读的流.
System.out.println("压缩文件创建完毕");
}
}catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
String zipName=filePackName+".zip";
String downLoadPath =filePathPack+filePackName+".zip";
File zipfile=new File(filePathPack+filePackName+".zip"); //压缩后的文件夹
//压缩文件
ZipOutputStream zos = null; //
try{
long start = System.currentTimeMillis();
FileInputStream fis = null; //把文件信息读到内存中
//BufferedInputStream bus = null; //用流的方式读
FileOutputStream fos = null; //把信息写到文件中
File[] sourceFiles = file.listFiles(); //文件夹下的文件
if(null == sourceFiles || sourceFiles.length<1){
System.out.println("待压缩的文件目录:" + filePathPack+filePackName + "里面不存在文件,无需压缩.");
}else{
fos = new FileOutputStream(zipfile); //压缩文件的读流
zos = new ZipOutputStream(fos);
for(int i=0;i<sourceFiles.length;i++){
byte[] bufs = new byte[1024*10];
//创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
//读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
//bus = new BufferedInputStream(fis, 1024*10);
int len = 0;
/*while((read=bus.read(bufs, 0, 1024*10)) != -1){
zos.write(bufs,0,read);
} */
while((len = fis.read(bufs)) != -1){
zos.write(bufs, 0, len);
}
zos.closeEntry();
fis.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
/*fis.close();
bus.close();
fos.close();
zos.close();*/
}
}catch (Exception e) {
System.out.println("压缩出错");
e.printStackTrace();
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//导出这个文件夹
response.reset();
response.setContentType("application/force-download");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) zipfile.length());
response.setHeader("Content-Disposition","attachment;filename=" + new String(zipName.getBytes("gbk"), "iso8859-1")); // 设置文件的名称
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(zipfile));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
springboot把文件生成到打包的target下,这样便于寻找
String realPath=ResourceUtils.getURL("classpath:").getPath(); //这个是定位到springboot项目下的静态资源位置,也就是resouces目录下
String fileName=realPath+"file/abc.xlsx" //这个就是文件的位置,最终会定位到项目target目录下的 file/abc.xlsx 文件
File file=new File(fileName) //创建文件
if(!file.getParentFile().exists()){ //判断的时候,需要判断父目录是否存在,一定要先有父目录,再操作文件
file.getParentFile().mkdirs()
file.createNewFile();
}else{
file.delete();
file.getParentFile().mkdirs()
file.createNewFile();
}
FileOutputStream fileOutputStream=new FileOutputStream (file); //把文件读入流
workbook.write(fileOutputStream) //把excel工作簿写入文件流中
workbook.close();
fileOutputStream.close(); //关闭流
网上好的参考代码:https://blog.csdn.net/qq_35514348/article/details/86682670