1.使用NPOI将datagridview复选框选中行导出到桌面的excel中 2.点击控件,快速打开文件下的word模板
时间: 2024-02-15 22:02:39 浏览: 40
1. 使用 NPOI 将 DataGridView 复选框选中行导出到桌面的 Excel 中:
以下是一个示例代码,可以实现将 DataGridView 中选中的行数据导出到 Excel 文件中:
```csharp
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
private void btnExport_Click(object sender, EventArgs e)
{
// 创建 Excel 文档对象
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
// 获取选中的行数据
List<DataGridViewRow> rows = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["CheckBoxColumn"];
if (chk.Value != null && (bool)chk.Value)
{
rows.Add(row);
}
}
// 添加表头
IRow headerRow = sheet.CreateRow(0);
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dataGridView1.Columns[i].HeaderText);
}
// 添加数据行
for (int i = 0; i < rows.Count; i++)
{
DataGridViewRow row = rows[i];
IRow dataRow = sheet.CreateRow(i + 1);
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(row.Cells[j].Value.ToString());
}
}
// 保存 Excel 文件
using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Export.xls", FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
```
2. 点击控件,快速打开文件下的 Word 模板:
可以使用 Process.Start 方法来打开指定的 Word 模板文件,示例代码如下:
```csharp
private void btnOpenTemplate_Click(object sender, EventArgs e)
{
string templatePath = @"C:\Template.docx";
if (File.Exists(templatePath))
{
Process.Start(templatePath);
}
else
{
MessageBox.Show("模板文件不存在!");
}
}
```
在上述代码中,我们首先判断指定的模板文件是否存在,如果存在,则使用 Process.Start 方法打开该文件,如果不存在,则弹出提示框告知用户。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)