创建EXCLE 文档的例子

创建EXCLE 文档的例子

1. 选择 "References", 右键点击,选择"Add Reference..."
2. 选择 ".NET" , 选择 "Microsoft.Office.Interop.Execl ..."
3. 选择 OK
4. 检察 Properties 属性,检察 "Embed Interop Types" 是否为 True, 设置为True.

用下面的例子代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

namespace CreateExcelWorkbook
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] values = {4, 6, 18, 2, 1, 76, 0, 3, 11};

            CreateWorkbook(values, @"C:\SampleFolder\SampleWorkbook.xls");
        }

        static void CreateWorkbook(int[] values, string filePath)
        {
            Excel.Application excelApp = null;
            Excel.Workbook wkbk;
            Excel.Worksheet sheet;

            try
            {
                    // Start Excel and create a workbook and worksheet.
                    excelApp = new Excel.Application();
                    wkbk = excelApp.Workbooks.Add();
                    sheet = wkbk.Sheets.Add() as Excel.Worksheet;
                    sheet.Name = "Sample Worksheet";

                    // Write a column of values.
                    // In the For loop, both the row index and array index start at 1.
                    // Therefore the value of 4 at array index 0 is not included.
                    for (int i = 1; i < values.Length; i++)
                    {
                        sheet.Cells[i, 1] = values[i];
                    }

                    // Suppress any alerts and save the file. Create the directory 
                    // if it does not exist. Overwrite the file if it exists.
                    excelApp.DisplayAlerts = false;
                    string folderPath = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    wkbk.SaveAs(filePath);
            }
            catch
            {
            }
            finally
            {
                sheet = null;
                wkbk = null;

                // Close Excel.
                excelApp.Quit();
                excelApp = null;
            }
        }
    }
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值