使用C#在Excel中合并单元格

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

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

请帮帮我。

使用Interop可以获得一系列单元格,并在该范围内调用.Merge()方法。

 eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge(); 
 oSheet.get_Range("A1", "AS1").Merge(); 
 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; 

代码片段

 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 ; } } 

谢谢

你可以使用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(); 

拿一个string列表就好

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

并在任务之前匹配string。 它会帮助你bcz所有的合并单元格将具有相同的价值

这以适当的方式解决了这个问题

 // 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); 
 Worksheet["YourRange"].Merge();