C#WinForm打开编辑好的Excel模板,实现窗口保存,查看,删除操作
时间: 2023-10-24 22:07:43 浏览: 51
首先,需要引用Microsoft.Office.Interop.Excel命名空间,然后在窗体中添加一个DataGridView和三个按钮,分别对应保存、查看和删除操作。
在保存操作中,我们需要打开Excel模板文件,将DataGridView中的数据写入到Excel文件中,然后保存并关闭Excel文件。代码如下:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
private void btnSave_Click(object sender, EventArgs e)
{
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(@"C:\Path\To\Excel\Template.xlsx");
Excel.Worksheet worksheet = workbook.Worksheets["Sheet1"];
for(int i = 0; i < dataGridView1.Rows.Count; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
workbook.Save();
workbook.Close();
excel.Quit();
}
```
在查看操作中,我们需要打开Excel模板文件,读取其中的数据,然后将数据显示在DataGridView中。代码如下:
```csharp
private void btnView_Click(object sender, EventArgs e)
{
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(@"C:\Path\To\Excel\Template.xlsx");
Excel.Worksheet worksheet = workbook.Worksheets["Sheet1"];
int rowCount = worksheet.UsedRange.Rows.Count;
int columnCount = worksheet.UsedRange.Columns.Count;
for(int i = 2; i <= rowCount; i++)
{
DataGridViewRow row = new DataGridViewRow();
for(int j = 1; j <= columnCount; j++)
{
if(worksheet.Cells[i, j].Value != null)
row.Cells.Add(new DataGridViewTextBoxCell { Value = worksheet.Cells[i, j].Value.ToString() });
else
row.Cells.Add(new DataGridViewTextBoxCell { Value = "" });
}
dataGridView1.Rows.Add(row);
}
workbook.Close();
excel.Quit();
}
```
在删除操作中,我们需要删除Excel模板文件。代码如下:
```csharp
private void btnDelete_Click(object sender, EventArgs e)
{
File.Delete(@"C:\Path\To\Excel\Template.xlsx");
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)