Exporting a single Excel worksheet to an image format such as PNG or JPEG is useful for generating preview, exporting formatted reports, and embedding sheets in web pages or PDFs. คู่มือนี้แสดงวิธีการแปลงหนึ่งแผ่นงานจาก Excel workbook into images using Aspose.Cells for .NET.
บทนํา
Exporting a single Excel worksheet to an image format (e.g., PNG, JPEG) is useful when generating previews, exporting charts, or sharing read-only visual representations of spreadsheet content. แนะนํานี้แสดงให้เห็นวิธีแปลงหนึ่งแผ่นงานจาก Excel workbook to an image using Aspose.Cells for .NET
กรณีการใช้งาน
- สร้างหน้าจอของแผ่นงานเฉพาะ
- การส่งออกรายงานแบบฟอร์มสําหรับอีเมลหรือเอกสาร
- รวมแผ่นเดียวในหน้าเว็บหรือ PDF
คู่มือขั้นตอน
ขั้นตอน 1: ติดตั้ง Aspose.Cells สําหรับ .NET
$ dotnet add package Aspose.Cells
ขั้นตอน 2: ดาวน์โหลดไฟล์ Excel
Workbook workbook = new Workbook("SalesData.xlsx");
Worksheet sheet = workbook.Worksheets["Q1 Report"]; // Access specific worksheet
ขั้นตอนที่ 3: การตั้งค่าตัวเลือกการถ่ายภาพ
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
OnePagePerSheet = true,
HorizontalResolution = 200,
VerticalResolution = 200,
PrintingPageType = PrintingPageType.Default
};
ขั้นตอน 4: สร้าง SheetRender Object
SheetRender renderer = new SheetRender(sheet, options);
ขั้นตอน 5: แปลงหน้าแต่ละหน้าไปยังรูปภาพ
for (int pageIndex = 0; pageIndex < renderer.PageCount; pageIndex++)
{
string imageName = $"worksheet_q1_page_{pageIndex + 1}.png";
renderer.ToImage(pageIndex, imageName);
}
ขั้นตอน 6: การบันทึกภาพ
รหัสนี้โดยอัตโนมัติบันทึกภาพหนึ่งต่อหน้าพิมพ์ในแผ่นงาน
ขั้นตอน 7: การปรับปรุงทางเลือก
คุณสามารถใช้การตั้งค่า layout เพิ่มเติม:
// Show gridlines in the output image
options.ShowGridLines = true;
// Fit all content on a single page
options.AllColumnsInOnePagePerSheet = true;
รหัสตัวอย่างเต็มรูปแบบ
using System;
using Aspose.Cells;
class Program
{
static void Main()
{
// Load the Excel workbook
Workbook workbook = new Workbook("SalesData.xlsx");
// Access a specific worksheet
Worksheet sheet = workbook.Worksheets["Q1 Report"];
// Define image rendering options
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
OnePagePerSheet = true,
HorizontalResolution = 200,
VerticalResolution = 200,
PrintingPageType = PrintingPageType.Default
};
// Enable gridlines if desired
options.ShowGridLines = true;
// Render the sheet to image(s)
SheetRender renderer = new SheetRender(sheet, options);
for (int pageIndex = 0; pageIndex < renderer.PageCount; pageIndex++)
{
string imageName = $"worksheet_q1_page_{pageIndex + 1}.png";
renderer.ToImage(pageIndex, imageName);
Console.WriteLine($"Saved: {imageName}");
}
Console.WriteLine("Worksheet successfully rendered to image(s).");
}
}
สภาพแวดล้อมทั่วไปและแก้ปัญหา
ปัญหา | โซลูชั่น |
---|---|
การตัดเนื้อหา | ใช้ AllColumnsInOnePagePerSheet = true |
ผลิตภัณฑ์ที่มีคุณภาพต่ํา | เพิ่มความละเอียดของภาพ |
สายเคเบิลที่หายไป | ชุด ShowGridLines = true |