从现有的base64编码中保存Excel文件

问题描述 投票:1回答:2

我具有Excel文件from this xml file的现有base64编码,我想将该数据(fileContent)保存到物理excel文件中,但是我坚持这样做。我已经看过一些有关如何对其进行编码的教程,但是我无法使它将数据保存到可以用Microsoft Excel打开的文件中。我尝试的解决方案将所有数据打印为excel条目(请参见附件图像)。我有asked a related question here,但我不知道编码的数据是实际的.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();
        }

    }

}
java excel sax
2个回答
1
投票

我不确定您要在方法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的内容(您已经在执行此操作)
  • 将此内容解码为字节数组
  • 将此字节数组保存在文件中(无需进行进一步的转换)

0
投票
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

需要RunTimePersmision

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);

}
© www.soinside.com 2019 - 2024. All rights reserved.