EPPLUS 4.5.3 复制表格
时间: 2024-05-15 18:16:06 浏览: 228
在EPPLUS 4.5.3中,可以通过以下步骤复制表格:
1. 获取要复制的源表格的范围,例如:
```csharp
ExcelRange sourceRange = worksheet.Cells["A1:D4"];
```
2. 使用`Copy`方法创建源表格的副本:
```csharp
ExcelRange copiedRange = sourceRange.Copy();
```
3. 将副本表格的范围设置为目标位置,例如:
```csharp
copiedRange.AutoFitColumns();
copiedRange.AutoFitRows();
copiedRange.Style.Border.BorderAround(ExcelBorderStyle.Thin);
copiedRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Cells["F1"].LoadFromText("Copied Table:");
worksheet.Cells["F2"].LoadFromText(" ");
worksheet.Cells["F3"].LoadFromText(" ");
worksheet.Cells["F4"].LoadFromText(" ");
worksheet.Cells["F1"].Style.Font.Bold = true;
worksheet.Cells["F1:F4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
copiedRange.CopyTo(worksheet.Cells["G1"]);
```
在这里,我们将副本表格的样式自适应列和行的宽度和高度,将单元格边框设置为细线条,水平居中和垂直居中。然后,我们将副本表格的范围复制到目标位置(这里是单元格“G1”)。
完整的示例代码如下:
```csharp
using OfficeOpenXml;
using OfficeOpenXml.Style;
class Program
{
static void Main(string[] args)
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Create source table
worksheet.Cells["A1"].Value = "Header1";
worksheet.Cells["B1"].Value = "Header2";
worksheet.Cells["C1"].Value = "Header3";
worksheet.Cells["D1"].Value = "Header4";
worksheet.Cells["A2"].Value = "Data1";
worksheet.Cells["B2"].Value = "Data2";
worksheet.Cells["C2"].Value = "Data3";
worksheet.Cells["D2"].Value = "Data4";
worksheet.Cells["A3"].Value = "Data5";
worksheet.Cells["B3"].Value = "Data6";
worksheet.Cells["C3"].Value = "Data7";
worksheet.Cells["D3"].Value = "Data8";
worksheet.Cells["A4"].Value = "Data9";
worksheet.Cells["B4"].Value = "Data10";
worksheet.Cells["C4"].Value = "Data11";
worksheet.Cells["D4"].Value = "Data12";
// Copy source table
ExcelRange sourceRange = worksheet.Cells["A1:D4"];
ExcelRange copiedRange = sourceRange.Copy();
copiedRange.AutoFitColumns();
copiedRange.AutoFitRows();
copiedRange.Style.Border.BorderAround(ExcelBorderStyle.Thin);
copiedRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
// Paste copied table
worksheet.Cells["F1"].LoadFromText("Copied Table:");
worksheet.Cells["F2"].LoadFromText(" ");
worksheet.Cells["F3"].LoadFromText(" ");
worksheet.Cells["F4"].LoadFromText(" ");
worksheet.Cells["F1"].Style.Font.Bold = true;
worksheet.Cells["F1:F4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
copiedRange.CopyTo(worksheet.Cells["G1"]);
package.SaveAs(new FileInfo("output.xlsx"));
}
}
}
```
阅读全文