C#操作PPT表格
1.激活组件
AxFramerControl改控件的dll自己再网上百度下下载这里不多讲
/// <summary>
/// 检测是否注册控件
/// </summary>
public static void CheckDsoFramerExists()
{
string path = @"c:\windows\system32\dsoframer.ocx";
string filepath = Application.StartupPath;
if (!File.Exists(path))
{
File.Copy(filepath + "\\dsoframer.ocx", path);
}
ProcessStartInfo psi = new ProcessStartInfo("regsvr32", "/s " + path);
Process.Start(psi);
}
2.开始操作写入表格
里面包含创建单元格 单元格复制 单元格字体居中 合并单元格等操作
/// <summary>
/// 创建人员分布表
/// </summary>
/// <param name="obj"></param>
public static void CreateTempPersonInfoByCom(object obj)
{
PPT.Presentation ppt = obj as PPT.Presentation;
if (ppt == null) { return; }
//清楚ppt现有内容
int slides = ppt.Slides.Count;
for (int i = 0; i < slides; i++)
{
ppt.Slides[1].Delete(); ;
}
ppt.Slides.Add(1, PPT.PpSlideLayout.ppLayoutTable);
foreach (PPT.Slide item in ppt.Slides)
{
item.Shapes.Range(1).Delete();
item.Shapes.Range(1).Delete();
item.Shapes.AddTable(7, 9, 10, 10, 700, 300);
PPT.Table table = item.Shapes.Range(1).Table;
if (table != null)
{
table.Cell(1, 1).Shape.TextFrame.TextRange.Text = "类别";
table.Cell(1, 2).Shape.TextFrame.TextRange.Text = "数量";
table.Cell(1, 3).Shape.TextFrame.TextRange.Text = "独立操作人员数量";
table.Cell(1, 4).Shape.TextFrame.TextRange.Text = "工龄分布";
table.Cell(1, 8).Shape.TextFrame.TextRange.Text = "每日人员变动情况";
table.Cell(1, 9).Shape.TextFrame.TextRange.Text = "备注";
table.Cell(2, 4).Shape.TextFrame.TextRange.Text = "入职五年以上";
table.Cell(2, 5).Shape.TextFrame.TextRange.Text = "入职3-5年";
table.Cell(2, 6).Shape.TextFrame.TextRange.Text = "入职1-3年";
table.Cell(2, 7).Shape.TextFrame.TextRange.Text = "入职1年以下";
table.Cell(3, 1).Shape.TextFrame.TextRange.Text = "正式";
table.Cell(4, 1).Shape.TextFrame.TextRange.Text = "试用";
table.Cell(5, 1).Shape.TextFrame.TextRange.Text = "实习";
table.Cell(6, 1).Shape.TextFrame.TextRange.Text = "劳务";
table.Cell(7, 1).Shape.TextFrame.TextRange.Text = "合计";
//循环设置单元格样式
SetTableStyle(table);
//设置合并操作
table.Cell(1, 1).Merge(table.Cell(2, 1));
table.Cell(1, 2).Merge(table.Cell(2, 2));
table.Cell(1, 3).Merge(table.Cell(2, 3));
table.Cell(1, 8).Merge(table.Cell(2, 8));
table.Cell(1, 9).Merge(table.Cell(2, 9));
table.Cell(1, 4).Merge(table.Cell(1, 7));
}
}
}
//设置样式
/// <summary>
/// 设置table样式
/// </summary>
/// <param name="table"></param>
private static void SetTableStyle(PPT.Table table)
{
if (table == null) { return; }
//循环设置单元格样式
for (int i = 0; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
table.Cell(i + 1, j + 1).Shape.TextFrame.TextRange.Font.Size = 14;
table.Cell(i + 1, j + 1).Shape.TextFrame.HorizontalAnchor = MsoHorizontalAnchor.msoAnchorCenter;
table.Cell(i + 1, j + 1).Shape.TextFrame.VerticalAnchor = MsoVerticalAnchor.msoAnchorMiddle;
}
}
}
3.效果图如下