c# - EPPlus 将工作表从 Workbook1 复制到 Workbook2
问题描述
我有一个带有名为 的工作表的模板工作簿ProdData
,我需要将此工作表复制到我当前的工作簿中。
使用 C# 和 EPPlus,如何将工作表从一个工作簿复制到另一个工作簿?当我查看智能感知时,它似乎只表明我可以从同一个工作簿中复制。
如何将工作表复制到新工作簿?
解决方案
这对我有用。
public static void CopySheetValues(string sourcePath, string sheetName, string destPath)
{
using (var src = new ExcelPackage(new FileInfo(sourcePath)))
using (var dest = new ExcelPackage(new FileInfo(destPath)))
{
var wsSrc = src.Workbook.Worksheets[1];
var wsDest = dest.Workbook.Worksheets[wsSrc.Name] ?? dest.Workbook.Worksheets.Add(wsSrc.Name);
for (var r = 1; r <= wsSrc.Dimension.Rows; r++)
{
Console.WriteLine("Row: " + r.ToString());
for (var c = 1; c <= wsSrc.Dimension.Columns; c++)
{
Console.WriteLine("Column: " + c.ToString());
var cellSrc = wsSrc.Cells[r, c];
var cellDest = wsDest.Cells[r, c];
if (cellDest.ToString() == "E10")
{
}
Console.WriteLine(cellDest.ToString());
// Copy value
cellDest.Value = cellSrc.Value;
// Copy cell properties
cellDest.Style.Numberformat = cellSrc.Style.Numberformat;
cellDest.Style.Font.Bold = cellSrc.Style.Font.Bold;
if (cellSrc.Style.Fill.BackgroundColor.Rgb != null)
{
if (cellSrc.Style.Fill.BackgroundColor.Rgb != "")
{
var color = cellSrc.Style.Fill.BackgroundColor.Rgb;
cellDest.Style.Fill.PatternType = ExcelFillStyle.Solid;
cellDest.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#" + color));//.SetColor(color);
}
else
{
cellDest.Style.Fill.PatternType = ExcelFillStyle.Solid;
cellDest.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#808080"));//.SetColor(color);
}
}// TODO... Add any additional properties that you may want to copy over
cellDest.Style.HorizontalAlignment =
cellSrc.Style.HorizontalAlignment;
cellDest.Style.VerticalAlignment =
cellSrc.Style.VerticalAlignment;
cellDest.Style.Border.Right.Style =
cellSrc.Style.Border.Right.Style;
cellDest.Style.Border.Left.Style =
cellSrc.Style.Border.Left.Style;
cellDest.Style.Border.Top.Style = cellSrc.Style.Border.Top.Style;
cellDest.Style.Border.Bottom.Style =
cellSrc.Style.Border.Bottom.Style;
cellDest.Style.WrapText = cellSrc.Style.WrapText;
}
}
dest.Save();
}
}
推荐阅读
- mongodb - 如何连接到第三方 mongoDB?
- javascript - 左上角的按钮有两行,我需要一行
- java - 空闲时间后 JDBC 连接丢失
- python - 将参数从 Python 传递给 bash 不能按预期工作
- spring-boot - 尝试在 Spring Boot 应用程序中使用 Redis 作为缓存时出现存储库错误
- java - 使用 InetSocketAddress 创建 DatagramPacket,缺少构造函数
- javascript - 单页 Vue 应用程序仅在 https 上的 aws s3 上加载空白
- svn - 从命令行列出 SVN 的项目/分支/主干
- javascript - MySQL 在 Windows 上给了我“未知列”错误
- javascript - 使用顶部 div 和底部 div 背景创建一个渐变,将它们连接到中间 div