用c# 可以利用书签的方式在word文档中生成折线图,使用的是using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Graph;两个库文件,数据能传到word里,
public Form1()
{
InitializeComponent();
InitGrid();
}
private void InitGrid()
{
var dt = new System.Data.DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("CountryCode");
dt.Columns.Add("CityCode");
for (int i = 1; i < 2; i++)
{
var newRow = dt.NewRow();
newRow["Id"] = i.ToString();
dt.Rows.Add(newRow);
}
dataGridView1.DataSource = dt;
}
private void Form1_Load(object sender, EventArgs e)
{
}
//添加
private void button1_Click(object sender, EventArgs e)
{
var dt = dataGridView1.DataSource as System.Data.DataTable;
var newRow = dt.NewRow();
newRow["Id"] = dt.Rows.Count + 1;
dt.Rows.Add(newRow);
}
//删除
private void button2_Click(object sender, EventArgs e)
{
var selected = dataGridView1.SelectedRows;
var dt = dataGridView1.DataSource as System.Data.DataTable;
if (selected.Count > 0)
{
for (var i = 0; i < selected.Count; i++)
{
var row = selected[i];
dt.Rows.RemoveAt(row.Index);
}
}
}
//生成书签
private void button3_Click(object sender, EventArgs e)
{
var dt = ConvertDgvDataToTable(dataGridView1);
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = app.Documents.Add("D:\\Test.docx");
app = doc.Application;
doc.ActiveWindow.Visible = true;
InsertGraphtoBookmark("图表", dt, ref doc, ref app);
}
public Microsoft.Office.Interop.Graph.XlChartType ChartType = Microsoft.Office.Interop.Graph.XlChartType.xlLine;
public void InsertGraphtoBookmark(string strbookmark, System.Data.DataTable dt, ref Microsoft.Office.Interop.Word.Document wDoc, ref Microsoft.Office.Interop.Word.Application WApp)
{
int i, j;
object missing = System.Reflection.Missing.Value;
object oClassType = "MSGraph.Chart.8";
//获取书签对象,换句话,把光标移过来
object bookmark = strbookmark;
WApp.ActiveDocument.Bookmarks.get_Item(ref bookmark).Select();
//初始化一张图表
Microsoft.Office.Interop.Graph.Chart wdChart =
(Microsoft.Office.Interop.Graph.Chart)WApp.Selection.InlineShapes.AddOLEObject(ref oClassType, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing).OLEFormat.Object;
//wrdChart.Application.Visible = false;
//改变图表格式
wdChart.ChartType = ChartType;
wdChart.Application.PlotBy = Microsoft.Office.Interop.Graph.XlRowCol.xlColumns;//根据Y轴来画图表
Microsoft.Office.Interop.Graph.Axis axis = (Microsoft.Office.Interop.Graph.Axis)wdChart.Axes(1, 1);//设置X轴的属性
wdChart.Application.DataSheet.Cells.Clear();//清空表格的初始数据
//填充图表数据,起始的行号和列号都是1
for (i = 0; i < dt.Columns.Count; i++)//初始化列名
{
wdChart.Application.DataSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
for (i = 0; i < dt.Rows.Count; i++)//填充数据
{
for (j = 0; j < dt.Columns.Count; j++)
{
wdChart.Application.DataSheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
}
}
wdChart.ChartType = Microsoft.Office.Interop.Graph.XlChartType.xlLine;
//更新图表并保存退出
wdChart.Application.Update();
wdChart.Application.Quit();
}
public static System.Data.DataTable ConvertDgvDataToTable(DataGridView dgv)
{
System.Data.DataTable dt = new System.Data.DataTable();
for (int count = 0; count < dgv.Columns.Count; count++)//循环DataGridView中的栏位
{
DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString());
dt.Columns.Add(dc);// 将DataGridView中栏位的标题写入到DataTable中
}
for (int count = 0; count < dgv.Rows.Count - 1; count++)//循环DataGridView中的资料行
{
DataRow dr = dt.NewRow();
for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
{
dr[countsub] = dgv.Rows[count].Cells[countsub].Value.ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
//生成曲线
private void button4_Click(object sender, EventArgs e)
{
var dt = ConvertDgvDataToTable(dataGridView1);
chart1.DataSource = dt;
chart1.Series[0].XValueMember = "CountryCode";//每周的字段显示在X轴
chart1.Series[0].YValueMembers = "CityCode";//每周对应的sum和显示在y轴
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Interval = 1;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Interval = 1;
this.chart1.ChartAreas["ChartArea1"].AxisX.Title = "电压";//X轴标题
this.chart1.ChartAreas["ChartArea1"].AxisY.Title = "转速";//X轴标题
this.chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;//不显示竖着的分割线
this.chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;//不显示竖着的分割线
this.chart1.Series[0].IsValueShownAsLabel = true;//显示坐标值
this.chart1.DataBind();
}
private void button5_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Word.Document doc = app.Documents.Add("D:\\Test.docx");
app = doc.Application;
doc.ActiveWindow.Visible = true;
foreach (Word.Bookmark bk in doc.Bookmarks)
{
if (bk.Name == "图表")
{
object oClassType = "MSGraph.Chart.8";
Graph.Axis axis;//x坐标
Word.Range range = bk.Range;
Graph.Chart wdchart = (Graph.Chart)range.InlineShapes.AddOLEObject(oClassType).OLEFormat.Object;
wdchart.Application.DataSheet.Cells.Clear();//清空数据集数据
//axis.MaximumScale = 1;//设置最大刻度
//填充数据集
int i, j;
for (i = 0; i < 2; i++)
{
wdchart.Application.DataSheet.Cells[i + 1, 1] = "列" + i.ToString();
}
for (i = 0; i < 2; i++)//填充数据
{
for (j = 0; j < 2; j++)
{
wdchart.Application.DataSheet.Cells[i + 2, j + 1] = i * j;
}
}
//根据y轴画图
wdchart.Application.PlotBy = Graph.XlRowCol.xlColumns;
//wdchart.Legend.Delete();
//wdchart.Height = 280;
//wdchart.Width = 600;
//更新图标并退出
wdchart.Application.Update();
wdchart.Application.Quit();
wdchart = null;
}
}
//doc.SaveAs("E:\\Test.docx");
//app.Quit();
}
private void button6_Click(object sender, EventArgs e)
{
var dt = ConvertDgvDataToTable(dataGridView1);
DataSet datast= dataGridView1.DataSource as System.Data.DataSet;
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = app.Documents.Add("D:\\Test.docx");
app = doc.Application;
doc.ActiveWindow.Visible = true;
AddChartByXiaominge(doc, datast, 10,10, ChartType, "D:\\Test.docx","tubaio");
}
public void InsertGraphtoBookmark1(string strbookmark, System.Data.DataTable dt, ref Microsoft.Office.Interop.Word.Document wDoc, ref Microsoft.Office.Interop.Word.Application WApp)
{
object missing = System.Reflection.Missing.Value;
object oClassType = "MSGraph.Chart.8";
//获取书签对象,换句话,把光标移过来
object bookmark = strbookmark;
WApp.ActiveDocument.Bookmarks.get_Item(ref bookmark).Select();
//初始化一张图表
Microsoft.Office.Interop.Graph.Chart wdChart =
(Microsoft.Office.Interop.Graph.Chart)WApp.Selection.InlineShapes.AddOLEObject(ref oClassType, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing).OLEFormat.Object;
//wrdChart.Application.Visible = false;
//改变图表格式
Microsoft.Office.Interop.Graph.Series s;
wdChart.Application.PlotBy = Microsoft.Office.Interop.Graph.XlRowCol.xlColumns;//根据Y轴来画图表
Microsoft.Office.Interop.Graph.Axis axis = (Microsoft.Office.Interop.Graph.Axis)wdChart.Axes(1, 1);//设置X轴的属性
s = (Microsoft.Office.Interop.Graph.Series)wdChart.SeriesCollection(0);
s.Shadow = false;
for (int i = 1; i < dt.Columns.Count; i++)
{
switch (i)
{
case 1:
s.Points(i).Interior.Color = Color.LightBlue;
break;
case 2:
s.Points(i).Interior.Color = Color.GreenYellow;
break;
case 3:
s.Points(i).Interior.Color = Color.Khaki;
break;
case 4:
s.Points(i).Interior.Color = Color.Wheat;
break;
case 5:
s.Points(i).Interior.Color = Color.DodgerBlue;
break;
case 6:
s.Points(i).Interior.Color = Color.CornflowerBlue;
break;
case 7:
s.Points(i).Interior.Color = Color.LightYellow;
break;
default:
s.Points(i).Interior.ColorIndex = 6 * i + 6;
break;
}
}
s.HasDataLabels = true;
//显示引导线
wdChart.SeriesCollection(0).HasLeaderLines = true;
//显示百分比
s.DataLabels().ShowPercentage = true;
s.DataLabels().Font.Size = 6;
//显示分组名
s.DataLabels().ShowCategoryName = true;
//不显示数值
s.DataLabels().ShowValue = false;
wdChart.ChartType = Microsoft.Office.Interop.Graph.XlChartType.xlLine;
//更新图表并保存退出
wdChart.Application.Update();
wdChart.Application.Quit();
}
public static void AddChartByXiaominge(Object oEndOfDoc, DataSet data, float height, float width, XlChartType chartType, string path, string title)
{
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application oWord;
Microsoft.Office.Interop.Word.Document oDoc = null;
oWord = new Microsoft.Office.Interop.Word.Application();
//打开word文档
try
{
oDoc = oWord.Documents.Open(path, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
catch (Exception e)
{
oWord.Quit(Type.Missing, Type.Missing, Type.Missing);
throw e;
}
//设置word界面为不可见
oWord.Visible = false;
if (true)
{
try
{
//插入chart
Microsoft.Office.Interop.Word.InlineShape oShape;
object oClassType = "MSGraph.Chart.8";
Microsoft.Office.Interop.Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);
object oChart = oShape.OLEFormat.Object;
object[] Parameters = new Object[1];
Parameters[0] = 4;
Microsoft.Office.Interop.Graph.Chart objChart = (Microsoft.Office.Interop.Graph.Chart)oShape.OLEFormat.Object;
Microsoft.Office.Interop.Graph.Application oChartApp = objChart.Application;
objChart.ChartType = chartType;
objChart.HasTitle = true;
objChart.ChartTitle.Text = title;
objChart.ChartTitle.Font.Size = 10;
objChart.PlotArea.Interior.Color = Color.White;
//绑定数据
DataSheet dataSheet;
dataSheet = objChart.Application.DataSheet;
dataSheet.Columns.Clear();
dataSheet.Rows.Clear();
System.Data.DataTable table = data.Tables[0];
for (int i = 1; i <= table.Rows.Count + 1; i++)
{
for (int j = 1; j <= table.Columns.Count; j++)
{
if (i == 1 && j != 1)
{
dataSheet.Cells[i, j] = table.Columns[j - 1].ColumnName;
}
else
{
if (!(i == 1 && j == 1))
{
dataSheet.Cells[i, j] = table.Rows[i - 2][j - 1];
}
}
}
}
Microsoft.Office.Interop.Graph.Series s;
Microsoft.Office.Interop.Graph.UpBars b;
if (chartType != XlChartType.xl3DPieExploded)
{
for (int i = 1; i <= table.Rows.Count; i++)
{
s = (Microsoft.Office.Interop.Graph.Series)objChart.SeriesCollection(i);
s.Shadow = false;
if (chartType == XlChartType.xlColumnClustered)
{
switch (i)
{
case 1:
s.Interior.Color = Color.LightBlue;
break;
case 2:
s.Interior.Color = Color.GreenYellow;
break;
case 3:
s.Interior.Color = Color.Khaki;
break;
case 4:
s.Interior.Color = Color.Wheat;
break;
case 5:
s.Interior.Color = Color.DodgerBlue;
break;
case 6:
s.Interior.Color = Color.CornflowerBlue;
break;
case 7:
s.Interior.Color = Color.LightYellow;
break;
default:
s.Interior.ColorIndex = 6 * i + 6;
break;
}
}
s.HasDataLabels = true;
s.DataLabels().Font.Size = 5;
}
objChart.Legend.Position = Microsoft.Office.Interop.Graph.XlLegendPosition.xlLegendPositionTop;
objChart.Legend.Height = 15;
objChart.Legend.Width = 150;
objChart.Legend.Left = objChart.ChartArea.Width / 2 - objChart.Legend.Width / 2;
}
else
{
objChart.HasLegend = false;
s = (Microsoft.Office.Interop.Graph.Series)objChart.SeriesCollection(1);
for (int i = 1; i < table.Columns.Count; i++)
{
switch (i)
{
case 1:
s.Points(i).Interior.Color = Color.LightBlue;
break;
case 2:
s.Points(i).Interior.Color = Color.GreenYellow;
break;
case 3:
s.Points(i).Interior.Color = Color.Khaki;
break;
case 4:
s.Points(i).Interior.Color = Color.Wheat;
break;
case 5:
s.Points(i).Interior.Color = Color.DodgerBlue;
break;
case 6:
s.Points(i).Interior.Color = Color.CornflowerBlue;
break;
case 7:
s.Points(i).Interior.Color = Color.LightYellow;
break;
default:
s.Points(i).Interior.ColorIndex = 6 * i + 6;
break;
}
}
s.HasDataLabels = true;
//显示引导线
objChart.SeriesCollection(1).HasLeaderLines = true;
//显示百分比
s.DataLabels().ShowPercentage = true;
s.DataLabels().Font.Size = 6;
//显示分组名
s.DataLabels().ShowCategoryName = true;
//不显示数值
s.DataLabels().ShowValue = false;
}
objChart.Application.Update();
oChartApp.Update();
oChartApp.Quit();
//宽
oShape.Width = width;
//高
oShape.Height = height;
oDoc.Save();
}
catch (Exception e)
{
throw e;
}
finally
{
//关闭word
oWord.Quit(Type.Missing, Type.Missing, Type.Missing);
}
}
else
{
//关闭word
oWord.Quit(Type.Missing, Type.Missing, Type.Missing);
throw new Exception("找不到书签" + oEndOfDoc.ToString());
}
}
}