CSV文件下载

本文详细介绍了如何使用Java生成CSV文件并进行流输出处理,包括流的创建、数据的写入、编码设置以及文件下载操作。主要内容涵盖CSV格式设置、数据分类输出、自定义标题生成、日期格式化和不同浏览器的文件名编码处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成流

 /**

     * CSV生成
     * @param comSelfDtoList
     */
    @SuppressWarnings("unchecked")

    private ByteArrayOutputStream main(BiForm biForm,int tab,String name) {

       //建立输出流

        OutputStreamWriter fw = null;

        String day = "";

       //捕获内存缓冲区

        ByteArrayOutputStream objBos = new ByteArrayOutputStream();
        try {
            String path = Constant.BI_FILE_DATA_DIR;
            File uploadFilePath = new File(path);
            StringBuffer write = new StringBuffer();
            //事業所名
            String officeName="";
            String office_Name="";
            if(uploadFilePath.exists() == false) {
            uploadFilePath.mkdirs();

            }

          //参数1 写入到哪   参数2 数据编码格式

            fw =  new OutputStreamWriter(objBos,"ms932");
            switch (tab) {
            case 1:  // 売上台帳
                day = biForm.year_tab1 +"年"+ biForm.month_tab1+"月";
                for(SalesLedgerDto salesLedgerDto : biForm.salesLedgerDtoList){
                    if(!office_Name.equals(salesLedgerDto.officeName)){
                        officeName = officeName+salesLedgerDto.officeName+"、";
                        office_Name = salesLedgerDto.officeName;
                    }
                }

                officeName = officeName.substring(0, officeName.length()-1);

                //   \r\n  CSV 出力时的换行表示  换格是逗号。 把要输入的文字以引号引起来 数据的逗号就不换格

                fw.write("\r\n");
                fw.write(YEARANDMONTH+","+day+"\r\n");
                fw.write(OFFICE_NAME+","+officeName+"\r\n");
                fw.write("\r\n");
                String string0 = ",,,,,,,,,";
                String string = ",,,,,,,,,";
                String strings = "事業所名,被保険者番号,お客様番号1,お客様番号2,保険者番号,利用者氏名,サービス種類,サービス提供日,審査日,";

                if(biForm.salesLedgerDtoList.get(0).flag1 >0){
                    string0 = string0 + ",,,,,,";
                    string = string + "介護保険請求額,,,,,,";
                    strings = strings + "国保連請求額,公費請求額,利用者負担額,公費利用者負担額,限度額超過額,小計,";
                }
                if(biForm.salesLedgerDtoList.get(0).flag2 >0){
                    string0 = string0 + ",,,,,,";
                    string = string+"医療保険請求額,,,,,,";
                    strings = strings + "国保連請求額,社会保険請求額,後期高齢,公費請求額,利用者負担額,小計,";
                }
                if(biForm.salesLedgerDtoList.get(0).flag3 >0){
                    string0 = string0 + ",,,";
                    string = string+"障害者福祉保健請求額,,,";
                    strings = strings + "国保連請求額,利用者負担額,小計,";
                }

                String titleName = "";
                int count1 = 0;
                // 自費のタイトル(非課税)
                StringBuilder strb1 = new StringBuilder();
                if (biForm.salesLedgerDtoList.get(0).taxTypeFlag1 > 0) {
                    for (SalesLedgerDto sedgerDto :biForm.salesLedgerDtoList) {
                        Iterator iterator = sedgerDto.res1.keySet().iterator();
                        while(iterator.hasNext()) {
                            titleName = iterator.next().toString();
                            if (!strb1.toString().contains(titleName)) {
                                strb1.append(titleName);
                                strb1.append(",");
                                count1++;
                            }
                        }
                    }
                }
                // 自費のタイトル(内税)
                int count2 = 0;
                StringBuilder strb2 = new StringBuilder();
                if (biForm.salesLedgerDtoList.get(0).taxTypeFlag2 > 0) {
                    for (SalesLedgerDto sedgerDto :biForm.salesLedgerDtoList) {
                        Iterator iterator = sedgerDto.res2.keySet().iterator();
                        while(iterator.hasNext()) {
                            titleName = iterator.next().toString();
                            if (!strb2.toString().contains(titleName)) {
                                strb2.append(titleName);
                                strb2.append(",");
                                count2++;
                            }
                        }
                    }
                }
                // 自費のタイトル(外税)
                int count3 = 0;
                StringBuilder strb3 = new StringBuilder();
                if (biForm.salesLedgerDtoList.get(0).taxTypeFlag3 > 0) {
                    for (SalesLedgerDto sedgerDto :biForm.salesLedgerDtoList) {
                        Iterator iterator = sedgerDto.res3.keySet().iterator();
                        while(iterator.hasNext()) {
                            titleName = iterator.next().toString();
                            if (!strb3.toString().contains(titleName)) {
                                strb3.append(titleName);
                                strb3.append(",");
                                count3++;
                            }
                        }
                    }
                }

                string0 = string0 + "自費,\r\n";
                if (strb1 != null) {
                    String str = "";
                    for (int k = 0; k < count1-1; k++) {
                        str = str + ",";
                    }
                    string = string + "非課税," + str;
                    strings = strings + strb1.toString();
                }
                if (strb2 != null) {
                    String str = "";
                    for (int k = 0; k < count2-1; k++) {
                        str = str + ",";
                    }
                    string = string + "内税," + str;
                    strings = strings + strb2.toString();
                }
                if (strb3 != null) {
                    String str = "";
                    for (int k = 0; k < count3-1; k++) {
                        str = str + ",";
                    }
                    string = string + "外税," + str;
                    strings = strings + strb3.toString();
                }
                string = string + "\r\n";
                strings = strings + "小計,利用者請求合計,合計\r\n";
                fw.write(string0);
                fw.write(string);
                fw.write(strings);

                String saleStr = salesLedgerCsv(biForm, strb1.toString(), strb2.toString(), strb3.toString());

                将数据写入到流

                fw.write(saleStr);

                将缓存中的数据都释放出来

                fw.flush();

                关闭流

                fw.close();
                break;
            case 2:  //サービス種別売上
                String outWrite = categoryCsv(biForm);
                fw.write(outWrite);
                fw.flush();
                fw.close();
                break;
            case 8:  // 介護・予防別売上
                day = biForm.year_tab8 +"年"+ biForm.month_tab8+"月";
                for(String tofficeName : biForm.tab8_officeName){
                    if(!office_Name.equals(tofficeName)
                            &&StringUtil.isNotEmpty(tofficeName)){
                        officeName = officeName+tofficeName+"、";
                        office_Name = tofficeName;
                    }
                }
                officeName = officeName.substring(0, officeName.length()-1);
                fw.write("\r\n");
                fw.write(YEARANDMONTH+","+day+"\r\n");
                fw.write(OFFICE_NAME+","+officeName+"\r\n");
                fw.write(",,,,年 月\r\n");
                fw.write("顧 客,,,");
                SimpleDateFormat dm = new SimpleDateFormat("yyyy年MM月");
                for(Date date : biForm.dateList){
                    fw.write(","+dm.format(date));
                }
                fw.write("\r\n");
                for(BiCareTypeDto biCareTypeDto : biForm.careTypeDtoList){
                    write = new StringBuffer();
                    write = careTypeCsv(biCareTypeDto);
                    fw.write(write.toString());
                }
                fw.flush();
                fw.close();
                break;
            case 9:  // 顧客数推移
                String tab9_csvstr = customerCntChangeCsv();
                fw.write(tab9_csvstr);
                fw.flush();
                fw.close();
                break;
            case 11:  //運営基準分析
                day = biForm.year_tab11 +"年"+ biForm.month_tab11+"月";
                for(BiConductDto biConductDto : biForm.conductList){
                    if(!office_Name.equals(biConductDto.officeName)
                            &&StringUtil.isNotEmpty(biConductDto.officeName)){
                        officeName = officeName+biConductDto.officeName+"、";
                        office_Name = biConductDto.officeName;
                    }
                }
                officeName = officeName.substring(0, officeName.length()-1);
                fw.write("\r\n");
                fw.write(YEARANDMONTH+","+day+"\r\n");
                fw.write(OFFICE_NAME+","+officeName+"\r\n");
                fw.write(",,,年月\r\n");
                fw.write("事業所名,サービス開発責任者名,担当");
                SimpleDateFormat fm = new SimpleDateFormat("yyyy年MM月");
                for(Date date : biForm.dateList){
                    fw.write(","+fm.format(date));
                }
                fw.write("\r\n");
                for(BiConductDto biConductDto : biForm.conductList){
                    fw.write("\""+biConductDto.officeName+"\",\""
                            +biConductDto.userName+"\",\""+biConductDto.flag+"\",\""
                            +biConductDto.monthflag1+"\",\""+biConductDto.monthflag2+"\",\""
                            +biConductDto.monthflag3+"\",\""+biConductDto.monthflag4+"\",\""
                            +biConductDto.monthflag5+"\",\""+biConductDto.monthflag6+"\",\""
                            +biConductDto.monthflag7+"\",\""+biConductDto.monthflag8+"\",\""
                            +biConductDto.monthflag9+"\",\""+biConductDto.monthflag10+"\",\""
                            +biConductDto.monthflag11+"\",\""+biConductDto.monthflag12+"\"\r\n"
                            );
                }
                fw.flush();
                fw.close();
                break;
            case 14:  // 自社利用率
                day = biForm.year_tab14 +"年"+ biForm.month_tab14+"月";
                for(BiComSelfDto biComSelfDto : biForm.comSelfDtoList){
                    if(!office_Name.equals(biComSelfDto.officeName)){
                        officeName = officeName+biComSelfDto.officeName+"、";
                        office_Name = biComSelfDto.officeName;
                    }
                }
                if(StringUtil.isNotEmpty(officeName)){
                officeName = officeName.substring(0, officeName.length()-1);
                }
                fw.write("\r\n");
                fw.write(YEARANDMONTH+","+day+"\r\n");
                fw.write(OFFICE_NAME+","+officeName+"\r\n");
                fw.write("\r\n");
                fw.write(",,,,,,"+BUY+"\r\n");
                fw.write(OFFICE_NAME+","+CAREMANAGER+","+SERVICETYPE+","+HOJINKBN +
                        ","+SVOSRVICENAME+","+VPOINT+","+EARNINGS+","+EARNINGS1+","+EARNINGS2+"\r\n");
                for(BiComSelfDto biComSelfDto : biForm.comSelfDtoList){
                    write = new StringBuffer();
                    write.append("\""+biComSelfDto.officeName+"\",\""+biComSelfDto.careManager+"\",\""
                            +biComSelfDto.serviceType+"\",\""+Transform(biComSelfDto.hojinKbn)+"\",\""
                            +biComSelfDto.svoSrviceName+"\",\""+fenge(biComSelfDto.vPoint)+"\",\""
                            +fenge(biComSelfDto.earnings)+"\"");
                    if (biComSelfDto.earnings1 != null) {
                        write.append(",\""+(biComSelfDto.earnings1.multiply(new BigDecimal("100"))).setScale(0)+"%\"");
                    } else {
                        write.append(",\""+NOTHING+"\"");
                    }
                    if (biComSelfDto.earnings2 != null) {
                        write.append(",\""+(biComSelfDto.earnings2.multiply(new BigDecimal("100"))).setScale(0)+"%\"");
                    } else {
                        write.append(",\""+NOTHING+"\"");
                    }
                    write.append("\r\n");
                    fw.write(write.toString());
                }
                fw.flush();
                fw.close();
            default:
                break;
            }
            } catch (IOException e) {

            }
            return objBos;

        }

总方法中的一部分

        name = name + "_" + dateStr + ".csv";

通过的上面的方法生成的流
        ByteArrayOutputStream objBos = main(biForm, tabNum,name);
        String fileCmt;

     根据浏览器的不同 使用不同的编码
        try {

       判断是不是IE
            if (request.getHeader("User-Agent").indexOf("MSIE") == -1) {
                    fileCmt = MimeUtility.encodeWord(name,
                            "ISO-2022-JP", "B");
            } else {
                    fileCmt = URLEncoder.encode(name, "UTF-8");
            }
            download(fileCmt,"csv",objBos);
        }
        catch (UnsupportedEncodingException e) {
        }

输出文件流

/**
         *  Fileダウンロード
         * @param fileName
         * @param in
         * @param size
         * @param ext
         * @throws IORuntimeException
         */
    private void download(String fileName, String ext,ByteArrayOutputStream objBos) throws IORuntimeException{
        try {
            HttpServletResponse response = ResponseUtil.getResponse();
            response.setHeader("Cache-Control","");
            response.setHeader("Pragma","");
            response.setHeader("Expires","-1");

            共同方法 最后取得 application/octet-stream
            response.setContentType(CommonUtil.getContentType(ext));
            response.setContentLength(objBos.size());
            response.setHeader("Content-disposition", "attachment; filename=\""
                    + fileName + "\"");
            OutputStream out = response.getOutputStream();
            try {
                //InputStreamUtil.copy(in, out);

                 将流输出
                byte[] aryByt = objBos.toByteArray();
                out.write(aryByt, 0, aryByt.length);
                OutputStreamUtil.flush(out);
            } finally {
                    objBos.close();
                    OutputStreamUtil.close(out);
            }
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值