问题
I am using Epplus to copy a worksheet from a wokbook and paste it in another workbook.I can able to copy the worksheet sucesssfully,by using the below code.
ExcelPackage masterPackage = new ExcelPackage(new FileInfo(@"C:\\Users\\350154\\Desktop\\vb workouts\\testsample.xlsx"));
ExcelPackage pckg = new ExcelPackage(new FileInfo("C:\\Users\\350154\\Desktop\\vb workouts\\as.xlsx"));
string workSheetName = pckg.Workbook.Worksheets[1].Name;
ExcelWorksheet pck = pckg.Workbook.Worksheets[1];
pck.ConditionalFormatting.RemoveAll();
masterPackage.Workbook.Worksheets.Add(workSheetName, pck);
The code copies the sheet sucessfully.But the copied sheet has formulas in their cells.So Values not copying in a new excel pls help me to solve this.
回答1:
If you're just looking to copy the values from one spreadsheet into a new sheet in another, try this:
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[sheetName];
var wsDest = dest.Workbook.Worksheets[wsSrc.Name] ?? dest.Workbook.Worksheets.Add(wsSrc.Name);
for (var r = 1; r <= wsSrc.Dimension.Rows; r++)
{
for (var c = 1; c <= wsSrc.Dimension.Columns; c++)
{
var cellSrc = wsSrc.Cells[r, c];
var cellDest = wsDest.Cells[r, c];
// Copy value
cellDest.Value = cellSrc.Value;
// Copy cell properties
cellDest.Style.Numberformat = cellSrc.Style.Numberformat;
cellDest.Style.Font.Bold = cellSrc.Style.Font.Bold;
// TODO... Add any additional properties that you may want to copy over
}
}
dest.Save();
}
}
UPDATE: Sample code updated to show how formatting can also be copied from the source to the destination worksheet
回答2:
Thanks @Pete. But I found a way to copy an entire worksheet to another workbook while I was looking for a different issue. https://github.com/JanKallman/EPPlus/issues/94
You change the below line to add the worksheet to the workbook.
var wsDest = m_GeneratedHeader.Workbook.Worksheets[wsSrc.Name] ?? m_GeneratedHeader.Workbook.Worksheets.Add(wsSrc.Name, wsSrc);
No need to use the two 'for' loops to iterate through rows and columns to copy each property. Adding the worksheet will copy cell style, font style, merge cells, etc... Worked for me.
Note that this was introduced after EPPlus 4.5.0.1
来源:https://stackoverflow.com/questions/45582359/copy-worksheet-in-epplus-values-only