Some Web projects use Excel as a report scheme, generate Excel files on the server side, and then transfer to the client for printing by the client. In the domestic environment, relative to PDF, the installation rate of Excel should be higher than the PDF reader installation rate, at the same time, Microsoft also for C # operations Excel provides a complete interface, although Zedgraph and other business reporting tools generated by the statistics are also very good, but others Microsoft is a big brand, Worthy of trust.
This article describes some of the ways in which you can use C # to invoke Excel to generate a statistical diagram (Chart) and to control each part of a Chart diagram.
In the previous report development using C # and Excel (ii)-operation statistics (Chart), we used a predefined Excel file to generate a statistical graph by changing a value in Chart. This article further demonstrates how to generate a statistical graph from the specified data from scratch.
First of all, add a reference to Excel, and then you need to define a few Excel objects to use:
Excel.Application ThisApplication = null;
Excel.Workbooks m_objBooks = null;
Excel._Workbook ThisWorkbook = null;
Excel.Worksheet xlSheet = null;
When creating a new _workbook object, the default will contain 3 sheet, so in order to show clarity, remove the extra sheet:
private void DeleteSheet()
{
foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets)
if (ws != ThisApplication.ActiveSheet)
{
ws.Delete();
}
foreach (Excel.Chart cht in ThisWorkbook.Charts)
cht.Delete();
}
Then you need to add the sheet to provide data to chart:
private void AddDatasheet()
{
xlSheet = (Excel.Worksheet)ThisWorkbook.
Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet,
Type.Missing, Type.Missing);
xlSheet.Name = "数据";
}
Generate the data used by chart because it is a demo, so use the method of generating random numbers instead of extracting data from the database.
private void LoadData()
{
Random ran = new Random();
for (int i = 1; i <= 12; i++)
{
xlSheet.Cells[i, 1] = i.ToString() + "月";
xlSheet.Cells[i, 2] = ran.Next(2000).ToString();
}
}