1、Word文件插入图表(通过Excel生成图表,再粘贴至Word文件)。
Excel.Shape shape = ((Excel.Worksheet)excelWorkbook.Worksheets[i + 1]).Shapes.AddChart();
Excel.Chart chart = shape.Chart;
chart.ChartType = Excel.XlChartType.xlLineMarkers;
string strPos = "D1:D" + iRowCount.ToString() + ", L1:M" + iRowCount.ToString();
Excel.Range rangeAll = excelWorksheet.Range[strPos];
chart.SetSourceData(rangeAll, Excel.XlRowCol.xlColumns);
Excel.Axis xAxis = (Excel.Axis)chart.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
xAxis.CategoryType = Excel.XlCategoryType.xlCategoryScale;
//插入图表
Word.Range wdRange = wordDoc.Range();
wdRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
wdRange.SetRange(wdRange.End, wdRange.End + 1);
chart.ChartArea.Copy();
Thread.Sleep(100);//延时很重要,否则执行下一句粘贴代码时,在无网络环境时会报错
wdRange.Paste();
Word.Shape wordShape = wdRange.InlineShapes[1].ConvertToShape();
wordShape.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;
wordShape.Top = 10;
wordShape.Left = 0;
wordDoc.Content.InsertAfter("\n");
wordApp.Selection.EndKey(ref unite, ref nothing);
2、Word文件插入表格
wordApp.Selection.EndKey(ref unite, ref nothing); //将光标移动到文档末尾
//设置表格的行数和列数
int iRowCount = LstRes[i].DtHis.Rows.Count + 1; //因为DataTable里无表头,则表的行数加1
int iColCount = LstRes[i].DtHis.Columns.Count;
//定义一个Word中的表格对象
Word.Table wordTable = wordDoc.Tables.Add(wordApp.Selection.Range, iRowCount, iColCount, ref nothing, ref nothing);
//默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
wordTable.Borders.Enable = 1;//这个值可以设置得很大,例如5、13等等
//设置table样式
wordTable.Range.Font.Name = "宋体";
wordTable.Range.Font.Size = 12;
wordTable.Range.Font.Bold = 1;
wordTable.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中
//添加列头
for (int iCol = 0; iCol < iColCount; iCol++)
{
wordTable.Cell(1, iCol + 1).Range.Text = LstRes[i].DtHis.Columns[iCol].ColumnName;
excelApp.Cells[1, iCol + 1] = LstRes[i].DtHis.Columns[iCol].ColumnName;
}
//添加表格内容
for (int iRow = 0; iRow < LstRes[i].DtHis.Rows.Count; iRow++)
{
for (int iCol = 0; iCol < LstRes[i].DtHis.Columns.Count; iCol++)
{
//wordTable.Cell(iRow + 2, iCol + 1).Range.HighlightColorIndex = Word.WdColorIndex.wdYellow;
wordTable.Cell(iRow + 2, iCol + 1).Range.Bold = 0;
wordTable.Cell(iRow + 2, iCol + 1).Range.Text = LstRes[i].DtHis.Rows[iRow][iCol].ToString();
excelApp.Cells[iRow + 2, iCol + 1] = LstRes[i].DtHis.Rows[iRow][iCol].ToString();
if (iCol == 4 || iCol == 11)
{
double dValue = LstRes[i].DtHis.Rows[iRow][iCol] == DBNull.Value ? 0 : Convert.ToDouble(LstRes[i].DtHis.Rows[iRow][iCol]);
if (dValue >= 150)
{
wordTable.Cell(iRow + 2, iCol + 1).Range.HighlightColorIndex = Word.WdColorIndex.wdYellow;
}
}
}
}
wordTable.Columns.AutoFit();
#endregion