C# 用C语言在Excel中合并单元格#

C# 用C语言在Excel中合并单元格#,c#,excel,C#,Excel,我有一个包含5个表的数据库。每个表包含24行,每行包含4列 我想在Excel工作表中显示这些记录。每个表的标题都是表的名称,但我无法合并标题的列 请帮帮我。使用Interop可以获得一个单元格区域,并在该区域上调用.Merge()方法 eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge(); 代码片段 public partial class Form1 : Form { public Form1() {

我有一个包含5个表的数据库。每个表包含24行,每行包含4列

我想在Excel工作表中显示这些记录。每个表的标题都是表的名称,但我无法合并标题的列


请帮帮我。

使用Interop可以获得一个单元格区域,并在该区域上调用
.Merge()
方法

eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge();
代码片段

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Excel.Application excelApp = null;
    private void button1_Click(object sender, EventArgs e)
    {
        excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
    }
}

谢谢

拿一张类似的字符串列表

List<string> colValListForValidation = new List<string>();
List colValListForValidation=newlist();

并在任务之前匹配字符串。它将帮助您bcz所有合并单元格将具有相同的值

这将以适当的方式解决问题

Excel.Application xl = new Excel.ApplicationClass();

Excel.Workbook wb = xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorkshe et);

Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

ws.Cells[1,1] = "Testing";

Excel.Range range = ws.get_Range(ws.Cells[1,1],ws.Cells[1,2]);

range.Merge(true);

range.Interior.ColorIndex =36;

xl.Visible =true;
// Merge a row
            ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
            ws.Range("B2:D3").Row(1).Merge();

您可以使用Microsoft.Office.Interop.Excel:

worksheet.Range[worksheet.Cells[rowNum,columnNum],worksheet.Cells[rowNum,columnNum]].Merge()

您还可以使用NPOI:

var cellsTomerge = new NPOI.SS.Util.CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
_sheet.AddMergedRegion(cellsTomerge);

你可以用NPOI来做

Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
试试看

ws.Range("A1:F2").Merge();

行和列从1开始。

您缺少一个参数-您可以将其放入
类型中。缺少
同意
Range.Merge(object-over)
,但实际上参数可以是bool。如果为true,则将指定范围的每行中的单元格合并为单独的合并单元格。如果为false或
键入.Missing
,则合并所有单元格。虽然此代码片段可能是解决方案,但确实有助于提高文章质量。请记住,您将在将来为读者回答这个问题,而这些人可能不知道您的代码建议的原因。YourRange是什么意思?Range是int,我想不是string。谢谢您提供的所有详细信息:)这基本上与C Ross给出的答案相同
Worksheet["YourRange"].Merge();
ws.Range("A1:F2").Merge();
using Excel = Microsoft.Office.Interop.Excel;
// Your code...
yourWorksheet.Range[yourWorksheet.Cells[rowBegin,colBegin], yourWorksheet.Cells[yourWorksheet.rowEnd, colEnd]].Merge();