首页 文章

使用C#在Excel中自动扩展格式化表格

提问于
浏览
0

我试图使用OLEDB在工作表的末尾插入一个新行 . 工作表在Range(a1:xx)中有一个格式表,其中存储了格式和公式 . 但OLEDB插件没有任何格式 .

我已经阅读了关于获取格式的帖子How to copy format of one row to another row in Excel with c#,但是并不认为它会得到公式 .

在Excel UI中,在格式化表格的右下角,会出现一个双箭头,我们可以拖动它以展开格式表范围 .

Image: What it looks like in the Excel

我们可以通过C#做什么?

谢谢 .

Excel.Range last = xlWS.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
        Excel.Range RngToCopyOri = xlWS.get_Range("A1", last).EntireRow;
        Excel.Range RngToCopy = RngToCopyOri.Resize[RngToCopyOri.Rows.Count + 1, RngToCopyOri.Columns.Count]; //because insert will add only 1 row, so the range would be one row larger
        Excel.Range RngToInsert = xlWS.get_Range("A1", Type.Missing).EntireRow;
        RngToInsert.Insert(Excel.XlInsertShiftDirection.xlShiftDown, RngToCopy.Copy(Type.Missing));

我试图将Range(A1,lowerleft cell)复制到原来的位置,但没有任何改变 .

1 回答

  • 0

    我尝试过Range.resize,autofill,autoformat . 所有这些都有一些问题 . 我终于放弃了使用OLEDB插入数据 . 相反,我用过

    worksheet.UsedRange.Item[rowNo,getColumnIndex(worksheet,columnTitle)]=value
    
    private int getColumnIndex(Excel.Worksheet sheetname, string header) {
            int index=0;
            Excel.Range activeRange=sheetname.UsedRange;
            for (int i = 1; i <= activeRange.Columns.Count; i++) {
                if (header == (string)(activeRange.Item[1,i] as Excel.Range).Value) {
                    index = i;
                }
            }
            if(index==0)
                throw some exception you like;
            return index;
        }
    

    getColumnIndex函数旨在定位SELECT [column]中的列...

    这样,格式表将自动扩展到您输入值的范围 .

相关问题