Create a windows form project,add a com reference named Microsoft Excel 16.0 Object Library
Create a Class named Excel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
namespace csharpexcelwritedata
{
class Excel
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
public Excel(string path, int Sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[Sheet];
}
public string ReadCell(int i, int j)
{
i++;
j++;
if (ws.Cells[i, j].Value2 != null)
return ws.Cells[i, j].value2;
else
return "";
}
public void WriteToCell(int i,int j,string s)
{
i++;
j++;
ws.Cells[i, j].Value2 = s;
}
public void Save()
{
wb.Save();
}
public void SaveAs(string path)
{
wb.SaveAs(path);
}
public void Close()
{
wb.Close();
}
}
}
Now go to the form code
private void Form1_Load(object sender, EventArgs e)
{
WriteData();
OpenFile();
}
public void WriteData()
{
Excel excel = new Excel(@"C:\Users\allso\source\repos\chsarpexcelpart1\chsarpexcelpart1\Test.xlsx", 1);
excel.WriteToCell(1, 1, "Hello I am writing");
excel.Save();
excel.SaveAs("Test2");
excel.Close();
}
public void OpenFile()
{
Excel excel = new Excel(@"C:\Users\allso\source\repos\chsarpexcelpart1\chsarpexcelpart1\Test.xlsx", 1);
MessageBox.Show(excel.ReadCell(1, 1));
excel.Close();
}
No comments:
Post a Comment