標籤:
網上找了很多方法,都沒有突出重點,著急著用,快速總結一下,把重點部分突出。
讀:ws.get_Range("A1", Type.Missing);
寫:ws.Cells[1, 1] = "修改的內容";
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Reflection;
using MSExcel = Microsoft.Office.Interop.Excel;
namespace ExcelTool
{
public partial class FrmMain : Form
{
string str = @"C:\Program Files\Data\SpaceKeyword.xlsx";
object missing = Missing.Value;
MSExcel.Application app = null;
MSExcel.Workbook wb = null;
MSExcel.Worksheet ws = null;
MSExcel.Range r = null;
/// <summary>
/// 載入Excel
/// </summary>
private void InitExcel()
{
//開啟excel
app = new Microsoft.Office.Interop.Excel.Application();
wb = app.Workbooks.Open(str, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
app.Visible = false;//讀Excel不顯示出來影響使用者體驗
//得到WorkSheet對象
ws = (MSExcel.Worksheet)wb.Worksheets.get_Item(1);
}
/// <summary>
/// 讀取Excel中的內容
/// </summary>
private void ReadExcel()
{
InitExcel();
//讀取A1儲存格內容
r = ws.get_Range("A1", Type.Missing);
string strA1 = r.Value;
app.Quit();//退出
MessageBox.Show(strA1);
}
/// <summary>
/// 寫入Excel(Win7下要以管理員身份運行才能修改)
/// </summary>
private void WriteExcel()
{
InitExcel();
ws.Cells[1, 1] = "修改的內容";
//儲存Excel
wb.Save();
wb.Close(null, null, null);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
ws = null;
wb = null;
app = null;
}
}
}
參考:http://greatverve.cnblogs.com/archive/2010/08/19/csharp-excel.html
以下是一些對excel的一些基本操作
1:工程對excel類庫的匯入,如:c:\program files\Microsoft office\offiece11\excel.exe
2:命名控制項的引入: using Microsoft.office.Interop.Excel;
3:如果是對一個已經存在的excel檔案進行操作則:
Application app=new Application();
Workbook wbook=app.Workbooks.Open("c:\\temp.xls",Type.Missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing);
Worksheet worksheet=(Worksheet)wbook.Worksheets[1];
4:如果是建立一個excel檔案:
Application app=new Application();
Workbook wbook=app.Workbook.Add(Type.missing);
Worksheet worksheet=(Worksheet)wbook.Worksheets[1];
5:設定某個儲存格裡的內容:
worksheet.Cells[1,2]="列內容"
6讀取某個儲存格裡的內容
string temp=((Range)worksheet.Cells[1,2]).Text;
7設定某個儲存格裡的格式
Excel.Range rtemp=worksheet.get_Range("A1","A1");
rtemp.Font.Name="宋體";
rtemp.Font.FontStyle="加粗";
rtemp.Font.Size=5;
8 儲存建立的內容:
worksheet.SaveAs("c:\\temp.xls",Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing);
url:http://greatverve.cnblogs.com/archive/2012/01/31/csharp-read-write-excel.html
C#讀寫Excel(轉)