导出到Excel时如何为列着色?

时间:2019-08-09 02:36:42

标签: c# excel

我有以下代码将数据导出到Excel工作表。我需要您的帮助才能知道如何用其他颜色为工作表列着色?

System.Data.DataTable dit = null;
try
{
    dit = BindGrid();
    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(dit, "Students");
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;filename=Download.xlsx");
        using (MemoryStream MyMemoryStream = new MemoryStream())
        {
            wb.SaveAs(MyMemoryStream);
            MyMemoryStream.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
        }
    }
}
catch (Exception Ex)
{
}
finally
{
    dit = null;
}

1 个答案:

答案 0 :(得分:0)

using Excel = using Microsoft.Office.Interop.Excel

public void ExportToExcel(DataGridView gridviewID, string excelFilename)
    {
        string path = excelFilename + ".xlsx";
        Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
        app.Visible = true;
        worksheet = workbook.Sheets["Sheet1"];
        worksheet = workbook.ActiveSheet;
        worksheet.Name = "Exported from gridview";
        for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
        {
            worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
        }
        for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
            }
            worksheet.Cells[i + 2, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
        }
        workbook.SaveCopyAs(path);
        workbook.Saved = true;
        workbook.Close();
        app.Quit();
    }