Export the dataGridView to Excel with all the cells format

后端 未结 3 1552
我寻月下人不归
我寻月下人不归 2020-11-27 06:37

I have this code that I know that it works fast

CopyAlltoClipboard(dataGridViewControl);
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office         


        
3条回答
  •  天命终不由人
    2020-11-27 06:51

    It seems that I found a solution using interop and EPPlus. I used the code above only to copy the values in Excel and then use this code below (EPPlus code) to take the format from dataGridView. This code depends or what you want to take from the dataGridView. In this code below I wanted to take the WrapText from the first row and the background colors from each written cell

    private void FinalizeWorkbook(DataTableReportParam reportParam, DataGridView dataGridViewControl)
    {
        FileInfo newFile = new FileInfo(reportParam.FileName);
        ExcelPackage pck = new ExcelPackage(newFile);
        IWorksheet worksheet = pck.Workbook.Worksheets[1];
    
        // wrap text and color the crashes with problems (header)
        for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
        {
            worksheet[1, col].WrapText = true;
            worksheet[1, col].AutofitRows();
            if (String.Compare(dataGridViewControl[col - 1, 0].Style.BackColor.Name, "0") != 0)
                worksheet[1, col].CellStyle.Color = dataGridViewControl[col - 1, 0].Style.BackColor;
        }
    
        // color the cells
        for (int row = 2; row <= worksheet.Dimension.End.Row; row++)
        {
            for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
            {
                if (String.Compare(dataGridViewControl[col - 1, row - 1].Style.BackColor.Name, "0") != 0)
                    worksheet[row, col].CellStyle.Color = dataGridViewControl[col - 1, row - 1].Style.BackColor;
            }
        }
        //save and dispose
        pck.Save();
        pck.Dispose();
    }
    

提交回复
热议问题