.net 操作EXCEL

法一:

參照C:/Program Files/Microsoft Visual Studio .NET 2003/SDK/v1.1/Samples/Technologies/Interop/Applications/Office/Excel/cs

 

using System;
using System.Reflection; // For Missing.Value and BindingFlags
using System.Runtime.InteropServices; // For COMException
using Excel;

class AutoExcel {
 
public static int Main() {
 
  Console.WriteLine (
"Creating new Excel.Application");
  Application app 
= new Application();
  
if (app == null{
   Console.WriteLine(
"ERROR: EXCEL couldn't be started!");
   
return 0;
  }

  
  Console.WriteLine (
"Making application visible");  
  app.Visible 
= true;
  
  Console.WriteLine (
"Getting the workbooks collection");
  Workbooks workbooks 
= app.Workbooks;

  Console.WriteLine (
"Adding a new workbook");
  
  
// The following line is the temporary workaround for the LCID problem
  _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);

  Console.WriteLine (
"Getting the worksheets collection");
  Sheets sheets 
= workbook.Worksheets;

  _Worksheet worksheet 
= (_Worksheet) sheets.get_Item(1);
  
if (worksheet == null{
   Console.WriteLine (
"ERROR: worksheet == null");
  }

  
  Console.WriteLine (
"Setting the value for cell");
  
  
// This paragraph puts the value 5 to the cell G1
     Range range1 = worksheet.get_Range("G1", Missing.Value);
  
if (range1 == null{
   Console.WriteLine (
"ERROR: range == null");
  }

  
const int nCells = 5;
  range1.Value2 
= nCells;
  
  
// This paragraph sends single dimension array to Excel
     Range range2 = worksheet.get_Range("A1""E1");
  
int[] array2 = new int [nCells];
  
for (int i=0; i < array2.GetLength(0); i++{
   array2[i] 
= i+1;
  }

  range2.Value2 
= array2;

  
// This paragraph sends two dimension array to Excel
     Range range3 = worksheet.get_Range("A2""E3");
  
int[,] array3 = new int [2, nCells];
  
for (int i=0; i < array3.GetLength(0); i++{
   
for (int j=0; j < array3.GetLength(1); j++{
    array3[i, j] 
= i*10 + j;
   }

  }

  range3.Value2 
= array3;

  
// This paragraph reads two dimension array from Excel
     Range range4 = worksheet.get_Range("A2""E3");
  Object[,] array4;
  array4 
= (Object[,])range4.Value2;
  
  
for (int i=array4.GetLowerBound(0); i <= array4.GetUpperBound(0); i++{
   
for (int j=array4.GetLowerBound(1); j <= array4.GetUpperBound(1); j++{
    
if ((double)array4[i, j] != array3[i-1, j-1]) {
     Console.WriteLine (
"ERROR: Comparison FAILED!");
     
return 0;
    }

   }

  }


  
// This paragraph fills two dimension array with points for two curves and sends it to Excel
     Range range5 = worksheet.get_Range("A5""J6");
  
double[,] array5 = new double[210];
  
for (int j=0; j < array5.GetLength(1); j++{
   
double arg = Math.PI/array5.GetLength(1* j;
   array5[
0, j] = Math.Sin(arg);
   array5[
1, j] = Math.Cos(arg);
  }

  range5.Value2 
= array5;
  
  
// The following code draws the chart
  range5.Select();
  ChartObjects chartobjects 
= (ChartObjects) worksheet.ChartObjects(Missing.Value);
  
  ChartObject chartobject 
= (ChartObject) chartobjects.Add(10 /*Left*/100 /*Top*/450 /*Width*/250 /*Height*/);
  _Chart chart 
= (_Chart) chartobject.Chart;
  
  
// Call to chart.ChartWizard() is shown using late binding technique solely for the demonstration purposes
  Object[] args7 = new Object[11];
  args7[
0= range5; // Source
  args7[1= XlChartType.xl3DColumn; // Gallery
  args7[2= Missing.Value; // Format
  args7[3= XlRowCol.xlRows; // PlotBy
  args7[4= 0// CategoryLabels
  args7[5= 0// SeriesLabels
  args7[6= true// HasLegend
  args7[7= "Sample Chart"// Title
  args7[8= "Sample Category Type"// CategoryTitle
  args7[9= "Sample Value Type"// ValueTitle
  args7[10= Missing.Value; // ExtraTitle
  chart.GetType().InvokeMember("ChartWizard", BindingFlags.InvokeMethod, null, chart, args7);
/*
ChartWizard(Source, Gallery, Format, P1otBy, CategoryLabels,
SeriesLabels, HasLegend, Title, CategoryTitle, ValueTitle, ExtraTitle)

  其中:

  Source:包含新圖表的源數據的區域。如省略,將修改活動圖表工作表或活動工作表中處於選定狀態的嵌人式圖表。

  Gallery:圖表類型。其值可爲下列常量之一:xlArea, x1Bar, xlColumn, xlLine, x1Pie, xlRadar,x1XYScatter, xlCombination, x13DArea, x13DBar、x13DColumn, x13DLine, x13DPie、x13 DSurface、xlDoughnut或xlDefaultAutoFormat。

  Format:內置自動套用格式的編號。如省略,將選擇默認值。

  P1otBy:指定系列中的數據是來自行(xlRows)還是列(xlColumns)。

  CategoryLabels:表示包含分類標誌的源區域內行數或列數的整數。

  SeriesLabels:表示包含系列標誌的源區域內行數或列數的整數。

  HasLegend:若指定True,則圖表將具有圖例。

  Title:圖表標題文字。

  CategoryTitle:分類軸標題文字。

  ValueTitle:數值軸標題文字。

  ExtraTitle:三維圖表的系列軸標題,或二維圖表的第二數值軸標題
http://www.cnblogs.com/pincelee/archive/2006/05/09/394684.html 
Excel中設置基本柱形圖格式) 
 

        chart.Legend.Delete(); 刪除系列名稱

        chart.ChartArea.Interior.ColorIndex = 1; 設置chartArea 顏色
        
        chart.PlotArea.Interior.ColorIndex = 40; 設置 PlotArea顏色
      
        Axis col= (Axis) chart.Axes(XlAxisType .xlValue, XlAxisGroup.xlPrimary );
        col.TickLabels.Font.Size= 8; 改變座標軸字體大小
        Axis row = (Axis)chart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
        row.TickLabels.Font.Size = 8;
*/
 

    
  Console.WriteLine (
"Press ENTER to finish the sample:");
  Console.ReadLine();  
  
  
try {
   
// If user interacted with Excel it will not close when the app object is destroyed, so we close it explicitely
   workbook.Saved = true;
   app.UserControl 
= false;
   app.Quit();
  }
 catch (COMException) {
   Console.WriteLine (
"User closed Excel manually, so we don't have to do that");
  }

  
  Console.WriteLine (
"Sample successfully finished!");
  
return 100;
 }

}

 

法二:像操作數據庫一樣操作

 

using System ;
using System.Drawing ;
using System.Collections ;
using System.ComponentModel ;
using System.Windows.Forms ;
using System.Data ;
using System.Data.OleDb ;
public class Form1 : Form
{
private Button button1 ;
private System.Data.DataSet myDataSet ;
private DataGrid DataGrid1 ;
private System.ComponentModel.Container components = null ;

public Form1 ( )
{
file:
//初始化窗體中的各個組件
InitializeComponent ( ) ;
file:
//打開數據鏈接,得到數據集
GetConnect ( ) ;
}

file:
//清除程序中使用過的資源
protected override void Dispose ( bool disposing )
{
if ( disposing )
{
if ( components != null ) 
{
components.Dispose ( ) ;
}

}

base.Dispose ( disposing ) ;
}


private void GetConnect ( )
{
file:
//創建一個數據鏈接
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = c:/sample.xls;Extended Properties=Excel 8.0" ;
OleDbConnection myConn 
= new OleDbConnection ( strCon ) ;
string strCom = " SELECT * FROM [Sheet1$] " ;
myConn.Open ( ) ;
file:
//打開數據鏈接,得到一個數據集
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
file:
//創建一個 DataSet對象
myDataSet = new DataSet ( ) ;
file:
//得到自己的DataSet對象
myCommand.Fill ( myDataSet , "[Sheet1$]" ) ;
file:
//關閉此數據鏈接
myConn.Close ( ) ;
}

private void InitializeComponent ( )
{
DataGrid1 
= new DataGrid ( ) ;
button1 
= new Button ( ) ;
SuspendLayout ( ) ;
DataGrid1.Name 
= "DataGrid1";
DataGrid1.Size 
= new System.Drawing.Size ( 400 , 200 ) ;

button1.Location 
= new System.Drawing.Point ( 124 , 240 ) ;
button1.Name 
= "button1" ;
button1.TabIndex 
= 1 ;
button1.Text 
= "讀取數據" ;
button1.Size 
= new System.Drawing.Size (84 , 24 ) ;
button1.Click 
+= new System.EventHandler ( this.button1_Click ) ;

this.AutoScaleBaseSize = new System.Drawing.Size ( 6 , 14 ) ;
this.ClientSize = new System.Drawing.Size ( 400 , 280 ) ;
this.Controls.Add ( button1 ) ;
this.Controls.Add ( DataGrid1 ) ;
this.Name = "Form1" ;
this.Text = "讀取Excle表格中的數據,並用DataGrid顯示出來!" ;
this.ResumeLayout ( false ) ;

}

private void button1_Click ( object sender , System.EventArgs e )
{
DataGrid1.DataMember
= "[Sheet1$]" ;
DataGrid1.DataSource 
= myDataSet ;

}

static void Main ( ) 
{
Application.Run ( 
new Form1 ( ) ) ;
}

}


  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章