EPPlus生成的Excel已损坏

时间:2020-02-13 02:44:41

标签: c# .net excel ms-office epplus

我正在使用以下代码使用EPplus将背景图像添加到Excel中。该文档在Polaris office中可以正常打开,但是在使用Excel时会出现以下错误

我们发现'filename.xlsx'中的某些内容存在问题。您是否想尽我们所能

代码

 foreach (var file in Filelist)
                {

                    // Load workbook
                    //var fileInfo = new FileInfo(@file);
                    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    //ExcelPackage pkg = new ExcelPackage(fs);

                    using (var package = new ExcelPackage(fs))
                    {

                        // Itterate through workbook sheets
                        foreach (var sheet in package.Workbook.Worksheets)
                        {

                            sheet.BackgroundImage.Image = bmp;
                            sheet.Protection.IsProtected = false;

                        }

                        package.SaveAs(new FileInfo(Path.GetFileNameWithoutExtension(file)+".xlsx"));
                    }
                    fs.Close();
                }

我检查了相关的SO问题,有人提到该问题可能是由于多次保存造成的。我确保单个文件的循环仅被命中一次。

更新: 生成位图的代码

 using (Graphics g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;         
                SizeF textSize = g.MeasureString("Sample", new Font(DefaultFont.FontFamily, 80));
                g.DrawString("Sample", new Font("Tahoma", 80), Brushes.Red, -(textSize.Width / 2), -(textSize.Height / 2));
            }

1 个答案:

答案 0 :(得分:0)

在我的示例中效果很好:

class EPPTest
{
public void CreateExcel(string filename)
{
    var fi = new FileInfo(filename);

    using (var excel = new ExcelPackage(fi) )
    using (var img = CreateImage() )
    {
        if( excel.Workbook.Worksheets.Count == 0 )
        {
            excel.Workbook.Worksheets.Add("MySheet");
        }

        foreach (var sheet in excel.Workbook.Worksheets)
        {

            sheet.BackgroundImage.Image = img;
            sheet.Protection.IsProtected = false;

        }

        excel.Save();// As(new FileInfo(Path.GetFileNameWithoutExtension(file) + ".xlsx"));
    }
}

public Image CreateImage()
{
    Bitmap img = new Bitmap(400, 400);

    using (Graphics g = Graphics.FromImage(img))
    using ( Font f = new Font("Tahoma", 80))
    {
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        SizeF textSize = g.MeasureString("Sample", f);
        g.DrawString("Sample", f, Brushes.Red, 0, (textSize.Height ));
    }

    return img;
}

}

以下是输出: Sample screenshot