Get Indent of Excel Cell in new column using C#

匆匆过客 提交于 2019-12-08 10:38:28

问题


My objective is to add a new column (B) which stores the indent level values (1,2,3..etc) of column A. I do this operation before loading the excel into c# excel object. So my object should have new column B with values of indent for column A.

if (xlWorkbook != null && xlWorkbook.Sheets.Count > 0)
{
    Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
    Excel.Range oRng = xlWorksheet.Range["B1"];

    oRng.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight,
    Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
    oRng = xlWorksheet.Range["B1"];
    oRng.Value2 = "IndentValue";

    Excel.Range xlHeaderRange = xlWorksheet.UsedRange;

    object[,] excelObj = (object[,])xlHeaderRange.Value2;

    string filename = Path.GetFileNameWithoutExtension(sFile);

    if (effectiveDate == DateTime.MinValue)
    {
        DateTime.TryParse(Convert.ToString((xlWorksheet.Cells[Definition.DATE_ROW_ID, Definition.DATE_COLUMN_ID] as Excel.Range).Value), out effectiveDate);
    }

    xlWorkbook.Close();
}

My problem:

  1. How to get the indent values in column B?

  2. The application pops up for save file as where i expect the workbook is saved automatically?

Appreciate your help.


回答1:


Here you go the answer,

if (xlWorkbook != null && xlWorkbook.Sheets.Count > 0)
{
         Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];

         //B8 position an column "IndentValue" in inserted 
         Excel.Range oRng = xlWorksheet.Range["B8"];
         oRng.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight,
         Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
         oRng = xlWorksheet.Range["B8"];
         oRng.Value2 = "IndentValue";

         //collect indent value of Col A in Col B
         for (i = 9; i <= xlWorksheet.UsedRange.Rows.Count; i++)
         {
             Excel.Range aRng = xlWorksheet.Range["A" + i];
             var Indentvalue = aRng.IndentLevel;
             xlWorksheet.Cells[i, 2].value = Indentvalue;
          }

         Excel.Range xlHeaderRange = xlWorksheet.UsedRange;

         object[,] excelObj = (object[,])xlHeaderRange.Value2;

         string filename = Path.GetFileNameWithoutExtension(sFile);

         if (staticconstList.Contains(filename))
           {
               if (effectiveDate == DateTime.MinValue)
                {
                    DateTime.TryParse(Convert.ToString((xlWorksheet.Cells[Definition.DATE_ROW_ID, Definition.DATE_COLUMN_ID] as Excel.Range).Value), out effectiveDate);
                }

                 xlWorkbook.Saved = true;
                 xlWorkbook.Close();
            }
}


来源:https://stackoverflow.com/questions/41561122/get-indent-of-excel-cell-in-new-column-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!