vc之ADO操作Excel

如何用 C++ + MFC
生成一个 带合并表头的.xsl文件
让后往里边插入数据

很早以前用过VC,现在用C#了。不过记得VC当初用的也是自动化对象,只要取得EXCEL的单元,想怎么设计表头,还不是自己写的事。
以下代码供您参考:
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbook excelWB = excelApp.Workbooks.Add(System.Type.Missing); //创建工作簿(WorkBook:即Excel文件主体本身)
Worksheet excelWS = (Worksheet)excelWB.Worksheets[1]; //创建工作表(即Excel里的子表sheet) 1表示在子表sheet1里进行数据导出
int nRange = 0;//最大范围
int nStartRow = 0;
foreach(DataGrid dg in dataGrids)
{
if (dg.Columns.Count() > nRange)
{
nRange = dg.Columns.Count();
}
}

char cMax = (char)((int)'A' + nRange);
if (nRange > 25)
{
nRange = 25;
cMax = 'Z';
}
// 如果数据中存在数字类型 可以让它变文本格式显示
//将数据导入到工作表的单元格
//写头:
if (strHeadList != null)
{
nStartRow = strHeadList.Count();
for (int i = 0; i < nStartRow; i++)
{
//int nHeight = strHeadList[0].Split('\n').Count();
Range range = (Range)excelWS.get_Range("A" + (i + 1).ToString(), cMax.ToString() + (i + 1).ToString()); //获取Excel多个单元格区域:本例做为Excel表头
range.Merge(0); //单元格合并动作 要配合上面的get_Range()进行设计
//range.RowHeight = 100;
range.Borders.LineStyle = 1; //设置单元格边框的粗细
//range.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb(); //设置单元格的背景色
range.WrapText=true; //文本自动换行
int count = Regex.Matches(strHeadList[i], "\n").Count;
range.RowHeight = (count+1) * 15;
//range.EntireRow.AutoFit();
range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.FromArgb(255, 204, 153).ToArgb()); //给单元格加边框
//range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //设置单元格上边框为无边框
//range.Interior.ColorIndex = 39; //填充颜色为淡紫色
//range.Font.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb(); //字体颜色
//range.EntireColumn.AutoFit(); //自动调整列宽
//range.HorizontalAlignment=XlHAlign.xlHAlignCenter; ; // 文本水平居中方式
//range.VerticalAlignment = VerticalAlignment.Center; //文本垂直居中方式
if (bIsTitle)
{
range.Font.Bold = true;
range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
range.get_Offset(0, 0).Cells.Value = strHeadList[i];
}
else
range.get_Offset(0, 0).Value = strHeadList[i];

}
}
温馨提示:答案为网友推荐,仅供参考
相似回答