工程例子下载:
http://download.csdn.net/detail/jiftlixu/6219503
一、添加COM对象引用
二、生成的效果
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//引用Excel Application類別
_Application myExcel = null;
//引用活頁簿類別
_Workbook myBook = null;
//引用工作表類別
_Worksheet mySheet = null;
//引用Range類別
Range myRange = null;
//開啟一個新的應用程式
myExcel = new Microsoft.Office.Interop.Excel.Application();
//加入新的活頁簿
myExcel.Workbooks.Add(true);
//停用警告訊息
myExcel.DisplayAlerts = false;
//讓Excel文件可見
// myExcel.Visible = true;
//引用第一個活頁簿
myBook = myExcel.Workbooks[1];
//設定活頁簿焦點
//myBook.Activate();
//引用第一個工作表
mySheet = (_Worksheet)myBook.Worksheets[1];
//命名工作表的名稱為 "Array"
mySheet.Name = "Cells";
//設工作表焦點
// mySheet.Activate();
int a = 0;
int UpBound1 = myData.GetUpperBound(0);//二維陣列數上限
int UpBound2 = myData.GetUpperBound(1);//二維陣列數上限
//寫入報表名稱
myExcel.Cells[1, 4] = "普通報表";
//以下的Select方法可省略,加速Excel運行,但VBA有些功能必須要用到Select方法。
//逐行寫入數據
for (int i = 0; i < UpBound1; i++)
{
for (int j = 0; j < UpBound2; j++)
{
//以單引號開頭,表示該單元格為純文字
a++;
//用offset寫入陣列資料
myRange = mySheet.get_Range("A2", Type.Missing);
myRange.get_Offset(i, j).Select();
myRange.Value2 = "'" + myData[i, j];
//用Cells寫入陣列資料
myRange.get_Range(myExcel.Cells[2 + i, 1 + j], myExcel.Cells[2 + i, 1 + j]).Select();
myExcel.Cells[2 + i, 1 + j] = "'" + myData[i, j];
}
}
//設定儲存路徑
string PathFile = Directory.GetCurrentDirectory() + @"\button4.xls";
//另存活頁簿
myBook.SaveAs(PathFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//關閉活頁簿
myBook.Close(false, Type.Missing, Type.Missing);
//關閉Excel
myExcel.Quit();
//釋放Excel資源
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
myBook = null;
mySheet = null;
myRange = null;
myExcel = null;
GC.Collect();
}
//以下是網路找來的陣列資料^^
private string[,] myData =
{
{ "車牌號", "類型", "品 牌", "型 號", "顏 色", "附加費證號", "車架號" },
{ "浙KA3676", "危險品", "貨車", "鐵風SZG9220YY", "白", "1110708900", "022836" },
{ "浙KA4109", "危險品", "貨車", "解放CA4110P1K2", "白", "223132", "010898" },
{ "浙KA0001A", "危險品", "貨車", "南明LSY9190WS", "白", "1110205458", "0474636" },
{ "浙KA0493", "上普貨", "貨車", "解放LSY9190WS", "白", "1110255971", "0094327" },
{ "浙KA1045", "普貨", "貨車", "解放LSY9171WCD", "藍", "1110391226", "0516003" },
{ "浙KA1313", "普貨", "貨車", "解放9190WCD", "藍", "1110315027", "0538701" },
{ "浙KA1322", "普貨", "貨車", "解放LSY9190WS", "藍", "24323332", "0538716" },
{ "浙KA1575", "普貨", "貨車", "解放LSY9181WCD", "藍", "1110314149", "0113018" },
{ "浙KA1925", "普貨", "貨車", "解放LSY9220WCD", "藍", "1110390626", "00268729" },
{ "浙KA2258", "普貨", "貨車", "解放LSY9220WSP", "藍", "111048152", "00320" }
};
}
}