1hiv2m
1hiv2m

Reputation: 33

C# - Export excel sheet to image using OpenXml SDK

I want to convert my excel sheet to an image with DocumentFormat.OpenXml.

My code is:

class Program
{
    static void Main()
    {
        String fileName = @"/Users/user/Downloads/Test.xlsx";
        String path = @"/Users/user/Downloads/Test.png";
        // Open the document for editing.
        using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))
        {
            WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();

            //OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
            //string text;
            //while (reader.Read())
            //{
            //    if (reader.ElementType == typeof(CellValue))
            //    {
            //        text = reader.GetText();
            //        Console.Write(text + " ");
            //    }
            //}
            //Console.WriteLine();

            //worksheetPart.Worksheet.Save();
            //workbookPart.Workbook.Save();
            spreadsheetDocument.SaveAs(path);

        }
    }
}

It gives an error:

Unhandled exception. System.IO.IOException: Cannot get stream with FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append when access is FileAccess.Read.
   at System.IO.Packaging.PackagePart.ThrowIfOpenAccessModesAreIncompatible(FileMode mode, FileAccess access)
   at System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
   at System.IO.Packaging.PackagePart.GetStream(FileMode mode)
   at DocumentFormat.OpenXml.Packaging.OpenXmlPart.GetStream(FileMode mode)
   at DocumentFormat.OpenXml.OpenXmlPartRootElement.SaveToPart(OpenXmlPart openXmlPart)
   at DocumentFormat.OpenXml.OpenXmlPartRootElement.Save()
   at Program.Main() in /Users/user/C#/Program.cs:line 36

How do I convert the read file to an image? Btw I could not use any other module.

Upvotes: 2

Views: 751

Answers (1)

Pe0067 PEOR
Pe0067 PEOR

Reputation: 74

Do you want to export image from cell or all of sheet? Because in your code you are trying to export text to image.In this case, you need to create image for example in picturebox and save it. You cannot save text like string to image. It's a different formats.

Instead of this,you can try to collect data from excel by OpenXML and paint it on pictureBox:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Arial", 14))
    {
        e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));
    }
}

After that, you can save image to .png from this pictureBox.

Upvotes: -1

Related Questions