Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从现有base64编码保存Excel文件_Java_Excel_Sax - Fatal编程技术网

Java 从现有base64编码保存Excel文件

Java 从现有base64编码保存Excel文件,java,excel,sax,Java,Excel,Sax,我有一个Excel文件的现有base64编码,我想将该数据(fileContent)保存到一个物理Excel文件中,但我一直在这样做。我看过一些关于如何编码的教程,但我无法让它将数据保存到可以用Microsoft Excel打开的文件中。我尝试的解决方案将所有数据打印为excel条目(见附图)。我有,但我不知道编码的数据是一个实际的.xls文件 下面是实现这一点的代码: package parsing; import java.io.BufferedInputStream; import ja

我有一个Excel文件的现有base64编码,我想将该数据(fileContent)保存到一个物理Excel文件中,但我一直在这样做。我看过一些关于如何编码的教程,但我无法让它将数据保存到可以用Microsoft Excel打开的文件中。我尝试的解决方案将所有数据打印为excel条目(见附图)。我有,但我不知道编码的数据是一个实际的.xls文件

下面是实现这一点的代码:

package parsing;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxSample {

    public static void main(String argv[]) {

        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

                StringBuilder value;

                @Override
                public void startElement(String uri, String localName,
                        String qName, Attributes attributes)
                        throws SAXException {
                    value = new StringBuilder();
                }

                @Override
                public void endElement(String uri, String localName,
                        String qName) throws SAXException {
                    if ("fileContent".equalsIgnoreCase(qName)) {
                        FileInputStream fis = null;
                        try {
                            String decodedValue = new String(DatatypeConverter.parseBase64Binary(value.toString()));
                            value.append(decodedValue);
                            // The name of the file to create.
                            String fileName = "temp.xls";
                            File file = new File(fileName);
                            fis = new FileInputStream(file);
                            BufferedInputStream inputStream = new BufferedInputStream(fis);
                            byte[] fileBytes = new byte[(int) file.length()];
                            inputStream.read(fileBytes);
                            inputStream.close();
                            System.out.println(qName + " = " + decodedValue);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(SaxSample.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(SaxSample.class.getName()).log(Level.SEVERE, null, ex);
                        } finally {
                            try {
                                fis.close();
                            } catch (IOException ex) {
                                Logger.getLogger(SaxSample.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    } else {
                        System.out.println(qName + " = " + value);
                    }
                    value = new StringBuilder();
                }

                @Override
                public void characters(char ch[], int start, int length)
                        throws SAXException {
                    value.append(new String(ch, start, length));
                }

            };

            saxParser.parse(new File("src/parsing/CON729.xml"), handler);
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }

}

我不确定您想在方法
endElement(…)
中做什么,但如果您想获得一个可读的excel文件,只需将编码的base64转换为字节数组(而不是另一个字符串)I。E更改您的
endElement(…)
如下所示:

@Override
public void endElement(String uri, String localName,
                       String qName) throws SAXException {
    if ("fileContent".equalsIgnoreCase(qName)) {
        try {
            Files.write(Paths.get("temp.xls"), DatatypeConverter.parseBase64Binary(value.toString()));
        } catch (IOException ex) {
            Logger.getLogger(SaxSample.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        // I'm still not sure why you're printing this ... debugging?
        System.out.println(qName + " = " + value);
    }
}
您唯一需要做的是:

  • 获取元素
    fileContent
    的内容(您已经在这样做了)
  • 将此内容解码为字节数组
  • 将此字节数组保存在文件中(无需进一步转换)

需要运行时个性化

public static void storetoExcelandOpen(Context context, String base,String name) {

    String root = Environment.getExternalStorageDirectory().toString();

    File myDir = new File(root + "/WorkBox");
    if (!myDir.exists()) {
        myDir.mkdirs();
    }

    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);

    String fname = name+n+".xlsx";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {

        FileOutputStream out = new FileOutputStream(file);
        byte[] excelAsBytes = Base64.decode(base, 0);
        out.write(excelAsBytes);
        out.flush();
        out.close();


    } catch (Exception e) {
        e.printStackTrace();
    }

    File dir = new File(Environment.getExternalStorageDirectory(), "WorkBox");
    File imgFile = new File(dir, fname);
    Intent sendIntent = new Intent(Intent.ACTION_VIEW);

    Uri uri;
    if (Build.VERSION.SDK_INT < 24) {
        uri = Uri.fromFile(file);
    } else {
        uri = Uri.parse("file://" + imgFile); // My work-around for new SDKs, causes ActivityNotFoundException in API 10.
    }

    sendIntent.setDataAndType(uri, "application/vnd.ms-excel");
    sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(sendIntent);

}
publicstaticvoidstoretoexcelandopen(上下文上下文、字符串基、字符串名){
String root=Environment.getExternalStorageDirectory().toString();
File myDir=新文件(root+“/WorkBox”);
如果(!myDir.exists()){
myDir.mkdirs();
}
随机生成器=新随机();
int n=10000;
n=发电机。下一个(n);
字符串fname=name+n+“.xlsx”;
File File=新文件(myDir,fname);
if(file.exists())
delete();
试一试{
FileOutputStream out=新的FileOutputStream(文件);
字节[]excelAsBytes=Base64.解码(base,0);
out.write(excelAsBytes);
out.flush();
out.close();
}捕获(例外e){
e、 printStackTrace();
}
File dir=新文件(Environment.getExternalStorageDirectory(),“WorkBox”);
File imgFile=新文件(dir,fname);
Intent sendIntent=新的Intent(Intent.ACTION\u视图);
Uri;
如果(Build.VERSION.SDK_INT<24){
uri=uri.fromFile(文件);
}否则{
uri=uri.parse(“文件://“+imgFile);//我对新SDK的处理导致API 10中的ActivityNotFoundException。
}
setDataAndType(uri,“application/vnd.ms excel”);
sendIntent.setFlags(Intent.FLAG\u活动\u新任务);
sendIntent.addFlags(Intent.FLAG\授予\读取\ URI\权限);
背景。起始触觉(sendIntent);
}
public static void storetoExcelandOpen(Context context, String base,String name) {

    String root = Environment.getExternalStorageDirectory().toString();

    File myDir = new File(root + "/WorkBox");
    if (!myDir.exists()) {
        myDir.mkdirs();
    }

    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);

    String fname = name+n+".xlsx";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {

        FileOutputStream out = new FileOutputStream(file);
        byte[] excelAsBytes = Base64.decode(base, 0);
        out.write(excelAsBytes);
        out.flush();
        out.close();


    } catch (Exception e) {
        e.printStackTrace();
    }

    File dir = new File(Environment.getExternalStorageDirectory(), "WorkBox");
    File imgFile = new File(dir, fname);
    Intent sendIntent = new Intent(Intent.ACTION_VIEW);

    Uri uri;
    if (Build.VERSION.SDK_INT < 24) {
        uri = Uri.fromFile(file);
    } else {
        uri = Uri.parse("file://" + imgFile); // My work-around for new SDKs, causes ActivityNotFoundException in API 10.
    }

    sendIntent.setDataAndType(uri, "application/vnd.ms-excel");
    sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(sendIntent);

}