Converting an Excel file into an image is one of the main features offered by Free Spire.XLS, which supports converting Excel files into PDF, XPS, SVG, HTML, and XML etc.
I will introduce my whole solution of converting Excel to an image in two parts. The first part describes how to save Excel to an image with default image quality. The second part shows how to convert Excel to a high-quality image by setting the image resolution. Then, you will find that the resulting image becomes very clear and the quality is very high. Here we go!
Below is the source code for converting the Excel worksheet to an image. Most image formats are supported, such as BMP, PNG, GIF, JPG, JPEG, TIFF and I will use JPG for example. It is very simple and I only need four lines of code.
- Workbook workbook = newWorkbook();
- workbook.LoadFromFile(@"..\..\SheetToImage.xlsx");
- Worksheet worksheet = workbook.Worksheets[0];
- worksheet.SaveToImage("sample.jpg", ImageFormat.Jpeg);
The properties of this image are given below.
Generally speaking, it meets most of the requirements but when we need a high quality image, the above performance is poor. So now, it comes to the second part of converting Excel to a high quality image by setting the image resolution, when saving Excel as an image.
- private void button1_Click(object sender, EventArgs e) {
- Workbook workbook = newWorkbook();
- workbook.LoadFromFile(@ "..\..\SheetToImage.xlsx");
- Worksheet worksheet = workbook.Worksheets[0];
-
- using(MemoryStream ms = newMemoryStream()) {
- worksheet.ToEMFStream(ms, 1, 1, worksheet.LastRow, worksheet.LastColumn);
-
- Image image = Image.FromStream(ms);
-
- Bitmap images = ResetResolution(image asMetafile, 300);
- images.Save("Result.jpg", ImageFormat.Jpeg);
- }
- this.Close();
- }
- private static Bitmap Reset Resolution(Metafile mf, float resolution) {
- int width = (int)(mf.Width * resolution / mf.HorizontalResolution);
- int height = (int)(mf.Height * resolution / mf.VerticalResolution);
- Bitmap bmp = newBitmap(width, height);
- bmp.SetResolution(resolution, resolution);
- Graphics g = Graphics.FromImage(bmp);
- g.DrawImage(mf, 0, 0);
- g.Dispose();
- return bmp;
- }
The properties of this image are mentioned below.
From the resulting page and comparing the differences between them, I hope you have a clear idea of how to save Excel as an image in C#.