NPOI - 从模板文件创建的保存工作簿

时间:2012-10-18 11:47:44

标签: asp.net asp.net-mvc excel asp.net-mvc-4 npoi

这是我第二次与NPOI打交道。我正在使用这样的模板excel文件创建工作簿。

        string dldir = AppDomain.CurrentDomain.BaseDirectory + "Download\\excel\\";
        string uldir = AppDomain.CurrentDomain.BaseDirectory + "Upload\\default_export_file\\";
        string filename = DateTime.Now.ToString("yyyy-M-d") + "_" + user.first_name + "_" + query.default_export_filename;

        System.IO.File.Delete(Path.Combine(dldir, filename));

        //System.IO.File.Copy(Path.Combine(uldir, query.default_export_filename), Path.Combine(dldir, filename));


        HSSFWorkbook hssfwb;
        using (FileStream file = new FileStream(Path.Combine(uldir, query.default_export_filename), FileMode.Open, FileAccess.ReadWrite))
        {
            hssfwb = new HSSFWorkbook(file);
        }

        MemoryStream mstream = new MemoryStream();
        hssfwb.Write(mstream);

        FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
        byte[] bytes = new byte[mstream.Length];
        mstream.Read(bytes, 0, (int)mstream.Length);
        xfile.Write(bytes, 0, bytes.Length);
        xfile.Close();
        mstream.Close();

但是当我检查创建的文件时。它什么都没有。大小是正确的。但内容只是空白。我也无法在MS Excel中打开它。我重复并追踪了代码,但我似乎无法找到导致它只写空白的原因。

任何人都知道为什么会发生这种情况

仅供参考:我正在使用从NuGet Gallery安装的VS 2010,ASP.Net MVC 4和NPOI 1.2.5

1 个答案:

答案 0 :(得分:11)

这个怎么样:

MemoryStream mstream = new MemoryStream();
hssfwb.Write(mstream);

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
byte[] bytes = new byte[mstream.Length];
mstream.Read(bytes, 0, (int)mstream.Length);
xfile.Write(bytes, 0, bytes.Length);
xfile.Close();
mstream.Close();

修改:

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
hssfwb.Write(xfile);
xfile.Close();