且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将单元格样式应用于上一行的新行中的每个单元格

更新时间:2023-02-04 19:50:26

找到答案其中



我正在寻找以下代码:

  workSheet.Cells [nRows + 1,3] = DateTime.Today; 
范围sourceRange = workSheet.Cells [nRows,3];
sourceRange.Copy(Type.Missing);
范围destinationRange = workSheet.Cells [nRows + 1,3];
destinationRange.PasteSpecial(XlPasteType.xlPasteFormats,XlPasteSpecialOperation.xlPasteSpecialOperationNone,false,false);
destinationRange.PasteSpecial(XlPasteType.xlPasteFormulas,XlPasteSpecialOperation.xlPasteSpecialOperationNone,false,false);

最后一行是复制公式。


I have an excel sheet which contains previously some values with some formatting. I would like to add a new row programmatically using c#. How can I apply styling of previous row to this newly added row during insert operation?

The code that I am using is as below:

Application excelApp = new Application();
            Workbooks workBooks = excelApp.Workbooks;
            Workbook workBook = excelApp.Workbooks.Open(fileName, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            int nTotalSheets = workBook.Worksheets.Count;

            Worksheet workSheet = workBook.Worksheets[1];
            int nColumns = workSheet.UsedRange.Columns.Count;
            int nRows = workSheet.UsedRange.Rows.Count;
            workSheet.Cells[nRows + 1, 1] = "Test";
            Range excelRange = workSheet.UsedRange;
            workBook.Close(true, fileName, false);
            Marshal.ReleaseComObject(workBook);

Found the answer here

I was looking for below code:

            workSheet.Cells[nRows + 1, 3] = DateTime.Today;
            Range sourceRange = workSheet.Cells[nRows, 3];
            sourceRange.Copy(Type.Missing);
            Range destinationRange = workSheet.Cells[nRows + 1, 3];
            destinationRange.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
            destinationRange.PasteSpecial(XlPasteType.xlPasteFormulas, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

The last line is for copying formulas.