简体   繁体   中英

excel getting the range programmatically

I've an excel report to be generated and below is the code that I've used. here I'm hardcoding the range ie from A to Z. is there a way to retrieve the Range based on the columns in dataset? Basically I just want to remove the hardcoded values.

strCol = String.Empty;
iRow = 0;

foreach (DataRow r in ds.Tables[0].Rows)
{
    iRow++;

    // add each row's cell data...
    iCol = 0;
    foreach (DataColumn c in ds.Tables[0].Columns)
    {
        iCol++;
        thisWorksheet.Cells[iRow + 1, iCol] = r[c.ColumnName];
        **strCol = "A" + (iRow + 1) + ":Z" + iCol;**
        thisWorksheet.Range[strCol].Borders.Weight = 2;
    }
}

for performance u could put the range in a object[,] and write it back in the end.

object[,] orange = range.value;

object[1,1] = "test";

range = orange;

I'm not 100% sure what you want to do, but you can get a Range like this:

Excel.Application excelApp = null;
Excel.Workbook wkbk;
Excel.Worksheet sheet;

excelApp = new Excel.Application();
wkbk = excelApp.Workbooks.Add();
sheet = wkbk.Sheets.Add() as Excel.Worksheet;

Excel.Range c1 = sheet.Cells[Row, Column]; //For instance Cells[1,1] for i think A1
Excel.Range c2 = sheet.Cells[Row, Column];
Excel.Range range = (Excel.Range)sheet.get_Range(c1,c2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM