7

这是我第二次与 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 库安装的 VS 2010、ASP.Net MVC 4 和 NPOI 1.2.5

4

1 回答 1

16

这个怎么样:</p>

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

修改:</p>

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
hssfwb.Write(xfile);
xfile.Close();
于 2012-10-18T17:49:46.847 回答