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

时间:2014-07-29 18:57:11

标签: java excel sax

我有一个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();
        }

    }

}

2 个答案:

答案 0 :(得分:1)

我不确定你在方法endElement(...)中尝试做什么,但如果你想获得一个可读的excel文件,只需将编码的base64转换为字节数组(NOT TO另一个字符串)我即像这样更改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的内容(您已经这样做了)
  • 将此内容解码为字节数组
  • 将此字节数组保存在文件中(无需进行进一步的转换)

答案 1 :(得分:1)

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

}