日期:2014-05-18  浏览次数:20976 次

C# 操作Excel文件
用C#实现一下功能:
  根据给定的完整文件名FilePath的Excel文件:
  首先判断文件是否存在,如果存在打开它向文件的表末尾添加新数据,如果不存在则创建他并打开向它的表中田间数据。

------解决方案--------------------
探讨
用C#实现一下功能:
    根据给定的完整文件名FilePath的Excel文件:
        首先判断文件是否存在,如果存在打开它向文件的表末尾添加新数据,如果不存在则创建他并打开向它的表中田间数据。

------解决方案--------------------
if (File.Exists(@"D:\\xxxx.xls"))
{
try
{
// 打开进行操作
}
catch (Exception ex)
{
MessageBox.Show("错误\r\n" + ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
Excel的打开和追加内容,你百度下就有了
------解决方案--------------------
给你操作Excel的代码,微软的
/****************************** Module Header ******************************\
* Module Name: Program.cs
* Project: CSAutomateExcel
* Copyright (c) Microsoft Corporation.

* The CSAutomateExcel example demonstrates how to use C# codes to create an 
* Microsoft Excel instance, create a workbook, and fill data into the 
* specified range, as well as how to clean up unmanaged COM resources and 
* quit the Excel application properly.

* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.

* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
#endregion


class Program
{
static void Main(string[] args)
{
object missing = Type.Missing;
Excel.Application oXL = null;
Excel.Workbooks oWBs = null;
Excel.Workbook oWB = null;
Excel.Worksheet oSheet = null;
Excel.Range oCells = null;
Excel.Range oRng1 = null;
Excel.Range oRng2 = null;


/////////////////////////////////////////////////////////////////////
// Create an instance of Microsoft Excel and make it invisible.
// 

oXL = new Excel.Application();
//Visible = true; //如果只想用程序控制该excel而不想让用户操作时候
oXL.Visible = false;
Console.WriteLine("Excel.Application is started");


/////////////////////////////////////////////////////////////////////
// Create a new Workbook.
// 

oWBs = oXL.Workbooks;
oWB = oWBs.Add(missing);
Console.WriteLine("A new workbook is created");


/////////////////////////////////////////////////////////////////////
// Get the active Worksheet and set its name.
// 

oSheet = oWB.ActiveSheet as Excel.Worksheet;
oSheet.Name = "Report";
Console.WriteLine("The active worksheet is renamed as Report");


/////////////////////////////////////////////////////////////////////
// Fill data into the worksheet's cells.
//