java-写入内容并下载生成文件

方法1:

maven依赖:
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
       	<!-- 文件下载依赖 -->
        <dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.6</version>
		</dependency>
/**
	 * 
	 * @param url 文件地址
	 * @param dir 存储目录
	 * @param fileName 存储文件名
	 * @return
	 */
	public static void downloadHttpUrl(String url, String dir, String fileName) {
		try {
			URL httpurl = new URL(url);
			File dirfile = new File(dir);  
	        if (!dirfile.exists()) {  
	        	dirfile.mkdirs();
	        }
			FileUtils.copyURLToFile(httpurl, new File(dir+fileName));
			System.out.println(new Date()+" info:"+url+" down success file!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


public static void main(String[] args) throws IOException {
		String fileName = "file1" + ".txt";
		String url = "http://192.168.1.82:8080/jiyingang-copy/" + fileName;
		FileWriter fw = new FileWriter("D:\\java\\tomcat\\apache-tomcat-8.0.52\\webapps\\jiyingang-copy\\" + fileName, true);//第二个参数为true,可实现内容追加写入,不执行覆盖操作
		fw.write("url,scratchCode");
		fw.write("\n");
		for(int i=0; i<4; i++) {
			fw.write("asdfghjkl==========================3");
			fw.write("\n");
		}
		
		fw.close();

		//url:可传本地绝对地址,也可以传链接地址
    	downloadHttpUrl("http://127.0.0.1:8080/project/20200409134823.txt",
    		"C:\\Users\\Administrator\\Desktop\\","20200409134823.txt");
	}

方法2:

public static void main(String[] args) throws IOException {
    	downLoadFromUrl("http://127.0.0.1:8080/project/20200409105217.txt",
    			"20200409105217.txt","C:\\Users\\Administrator\\Desktop");
	}
    /**
     * 
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        // 防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 得到输入流
        InputStream inputStream = conn.getInputStream();
        // 获取自己数组
        byte[] getData = readInputStream(inputStream);
        // 文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }

        System.out.println("info:" + url + " download success");

    }

    /**
     * 	从输入流中获取字节数组
     * 
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

方法3:通过HttpServlet实现对应模板的内容下载(空模板,或是存在行名称模板等),各层级结构代码实现如下:
maven依赖:

		<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.9</version>
        </dependency>

指定路径下的excel内容模板:

exceltemplate/修接口 查询.xlsx;将要导出的数据模板存放在项目中该路径下(也可以自定义路径,只要代码执行时可以找到对应的模板进行数据的写入即可)

读取excel模板工具类

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Excel处理相关工具
 */
public class ExcelUtils {

    /**
     * 设置单元格默认的格式
     *
     * @param cstyle
     * @param wb
     */
    public static void setDefaultStyle(XSSFCellStyle cstyle, XSSFWorkbook wb) {
        // 设置边框
        cstyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cstyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cstyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cstyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        XSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 10);
        font.setFontName("Calibri");
        cstyle.setFont(font);
        cstyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        cstyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    }

    /**
     * 获取默认的模板各列名称
     *
     * @param sheet
     * @return
     */
    public static List<String> getColumnTitile(XSSFSheet sheet) {
        List<String> list = new ArrayList<>();
        if (sheet != null) {
            int columIndex = 0;
            XSSFRow row = sheet.getRow(0);
            String column;
            Cell cell;
            while ((cell = row.getCell(columIndex++)) != null
                    && StringUtils.isNotBlank((column = getCellValue(cell)))) {
                list.add(column);
            }
        }
        return list;
    }

    /**
     * 获取单元格的内容
     *
     * @param cell
     * @return
     */
    private static String getCellValue(Cell cell) {
        String value = "";
        if (null != cell) {
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    double d = cell.getNumericCellValue();
                    value = String.valueOf((int) d);
                    break;
                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    value = cell.getStringCellValue().trim();
                    break;
            }
        }
        return value;
    }

    /**
     * 	填充MapList格式的Excel
     *
     * @param list
     * @param sheet
     * @param cstyle
     * @param row
     * @param cell
     * @param columnList
     */
    public static void SetExcelForMapList(List<Map<String, Object>> list, XSSFSheet sheet, XSSFCellStyle cstyle, XSSFRow row, XSSFCell cell, List<String> columnList) {
        {
            if (list != null && list.size() > 0) {
                int rowInt = 0;
                int nullNum = 0;
                for (int i = 0; i < list.size(); i++) {
                	Map<String, Object> m = list.get(i);
                	if(null == m) {
                		nullNum ++;//记录空白行数
                		continue;
                	}
                    rowInt = i - nullNum + 1;//去空白行
                    row = sheet.createRow(rowInt);
                   //填充列
                   for(int j=0;j<columnList.size();j++){
                       cell=row.createCell(j);
                       cell.setCellValue(null == m.get(columnList.get(j))? "" :
                               m.get(columnList.get(j)).toString());
                   }
                }
            }
        }
    }
}

mapper.xml:

<!-- 
	注意:在mybatis框架中,使用数据库的'<>'需要转移,否则与框架冲突
	转义格式如下:Lot_no <![CDATA[ <> ]]> "120507") ,或者也可以使用'!='
 -->
<select id="selectWorkForm3FixInterface" resultType="java.util.HashMap">
  	SELECT 
		FJ_date AS '复检日期', 
		LOT_NO, 
		CONCAT(REEL_NO_1,'-',REEL_NO_2,'-',REEL_NO_3) AS '单号',
		XJK_QTY AS '修接口'
	FROM 
		work_form_3
	ORDER BY 
		FJ_date, 
		LOT_NO, 
		CONCAT(REEL_NO_1,'-',REEL_NO_2,'-',REEL_NO_3)
  </select>

mapper:

List<Map<String,Object>> selectWorkForm3FixInterface();

service:

接口:
public List<Map<String,Object>> selectWorkForm3FixInterfaceDownload();
实现类:
@Override
public List<Map<String, Object>> selectWorkForm3FixInterfaceDownload() {
	return workForm3Mapper.selectWorkForm3FixInterface();
}

controller:

@ApiOperation(value = "修接口 查询导出")
    @GetMapping("workForm3FixInterfaceDownload")
	public void workForm3FixInterfaceDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
		InputStream inputStream = null;
		try {
			inputStream = WorkFormController.class.getClassLoader()
					.getResourceAsStream("exceltemplate/修接口 查询.xlsx");
		} catch (Exception e) {
			log.error("-----------读取模板失败-------------");
            throw new RuntimeException("读取模板失败");
		}
		XSSFWorkbook wb = new XSSFWorkbook(inputStream);
		XSSFSheet sheet = wb.getSheetAt(0);
        XSSFCellStyle cstyle = wb.createCellStyle();
        ExcelUtils.setDefaultStyle(cstyle, wb);
        // 数据处理
        XSSFRow row = null;
        XSSFCell cell = null;
        //数据
        List<Map<String,Object>> list = workFormService.selectWorkForm3FixInterfaceDownload();
        //获取模板各列字段
        List<String> columnList = ExcelUtils.getColumnTitile(sheet);
        //公用的Excel数据写入,支持List>格式的数据
        ExcelUtils.SetExcelForMapList(list, sheet, cstyle, row, cell, columnList);
        // 末尾
        StringBuffer tempFileName = new StringBuffer();
        tempFileName.append("修接口 查询");
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        response.setContentType("application/vnd.ms-excel");
        String filename = tempFileName.toString();
        // 解决空格变+问题
        String codeFileName = URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
        if (agent.contains("firefox")) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1") + ".xlsx");
        } else {
            response.setHeader("Content-Disposition", "attachment; filename=" + codeFileName + ".xlsx");
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            wb.write(outputStream);
        } catch (Exception e) {
            throw new RuntimeException("写入Excel失败");
        } finally {
            outputStream.flush();
            outputStream.close();
        }
	}

你可能感兴趣的:(java-写入内容并下载生成文件)