準(zhǔn)備工作
1、添加引用
在引用位置點擊右鍵點擊管理NUGet程序包
搜索Excel,在搜索結(jié)果中點擊Microsoft.Office.Interop.Excel
然后點擊安裝即可,搜不到的話,在右側(cè)程序包源位置改成全部再次搜索
。
添加類文件
對準(zhǔn)項目,點擊右鍵,在彈出菜單選擇添加,選擇類類名稱隨意,然后清空新建類得到全部內(nèi)容,把下面封裝號的源代碼全部粘貼進(jìn)去,項目名稱改成你自己原本的項目名稱。
源代碼
1、封裝好的類
文章來源:http://www.zghlxwxcb.cn/news/detail-648912.html
using System;
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;
namespace 改成你自己的項目名稱
{
internal class ExcelChange
{
/// <summary>
/// Excel寫入數(shù)據(jù),修改工作表單元格數(shù)值
/// </summary>
/// <param name="FileName">文件完整路徑</param>
/// <param name="WorksheetIndex">工作表索引值</param>
/// <param name="kv">單元格位置和數(shù)值</param>
public void Excel寫入數(shù)據(jù)(string FileName, int WorksheetIndex, SortedList<string, string> kv)
{
//創(chuàng)建excel應(yīng)用程序
Excel.Application myApp = new Excel.Application();
//打開文件
Excel.Workbook wb = myApp.Workbooks.Open(FileName);
//選擇工作表
Excel.Worksheet ws = wb.Worksheets[WorksheetIndex];//sheet的索引從1開始
//獲取工作表的名稱
string wsName = ws.Name;
Console.WriteLine(wsName);
//數(shù)據(jù)表的有效數(shù)據(jù)行數(shù)
int wsUsedRows = ws.UsedRange.Rows.Count;
Console.WriteLine(wsUsedRows);
//數(shù)據(jù)表的有效數(shù)據(jù)列數(shù)
int wsUsedColumns = ws.UsedRange.Columns.Count;
Console.WriteLine(wsUsedColumns);
foreach (string key in kv.Keys)
{
//修改數(shù)值
ws.Rows[ws.Range[key].Row].Cells[ws.Range[key].Column].Value = kv[key];
}
//保存文件、關(guān)閉文件
wb.Save();
wb.Close();
//退出excel應(yīng)用程序
myApp.Quit();
}
}
}
2、調(diào)用方法
using System;
using System.Collections.Generic;
using 項目名稱.Properties;
ExcelChange Ec = new ExcelChange();
private void button3_Click(object sender, EventArgs e)
{
SortedList<string, string> sl = new SortedList<string, string>
{
{ "A1", "qq" },
{ "A2", "qd" },
{ "C2", "qd" }
};
Ec.Excel寫入數(shù)據(jù)(@"D:\Users\toss\Desktop\123.xlsx", 1, sl);
}
未完待續(xù)
沒有用到新建,改變格式等操作,暫時不寫代碼了文章來源地址http://www.zghlxwxcb.cn/news/detail-648912.html
到了這里,關(guān)于C# WinForm 使用Microsoft.Office.Interop.Excel對Excel文件表格的單元格值進(jìn)行修改操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!