首页 > 解决方案 > 如何使用 C# .NET 为 excel 添加自动调整列数据

问题描述

 private void copyAlltoClipboard()
    {
        sdataGridView.SelectAll();
        DataObject dataObj = sdataGridView.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        copyAlltoClipboard();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Microsoft.Office.Interop.Excel.Application();
        
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
        
    }

我正在使用这段代码将我的datagridview数据导出到excel,但我想为包括标题的列文本添加自动调整或合并列数据。我不知道该怎么做。非常感谢任何帮助。

标签: c#winforms

解决方案


要调整列宽,您可以执行以下操作:

Excel.Range xlEntireColumn = null;
Excel.Range xlRange = null;

while (reader.Read()) {
for (int i=0;i<numcols;i++) { 
    xlsheet.ActiveSheet.Cells[row,i+1] = reader.GetValue(i).ToString();

    xlRange = xlSheet.ActiveSheet.Cells[row, i+1];
    xlEntireColumn = xlRange.EntireColumn;
    xlEntireColumn.AutoFit();
}

也检查一下.. https://www.dotnetfunda.com/codes/show/1071/export-to-excel-with-grid-color-in-winforms-using-csharp


推荐阅读