问题
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:
How to get the indent values in column B?
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