1.导出
使用winfrom简单做个界面
选择导出路径 + XLSX起名字
打开导出是XLSX文件
代码部分
// 创建Excel应用程序对象
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
// 创建工作簿
Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
// 填充数据
DataTable dt = GetDataTable(); // 获取数据源
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[i + 1, j + 1] = dt.Rows[i][j].ToString();
}
}
// 保存Excel文件
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel文件|*.xlsx";
saveFileDialog.Title = "保存Excel文件";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveFileDialog.FileName);
MessageBox.Show("导出成功!");
}
// 关闭Excel应用程序
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
private DataTable GetDataTable()
{
// 模拟数据源
DataTable dt = new DataTable();
dt.Columns.Add("姓名");
dt.Columns.Add("年龄");
dt.Columns.Add("性别");
dt.Rows.Add("张三", 20, "男");
dt.Rows.Add("李四", 25, "女");
dt.Rows.Add("王五", 30, "男");
return dt;
}
2.导入EXCE
创建一个简单的页面
下载插件 ExcelDataReader和ExcelDataReader.DataSet依赖项
文章来源:https://www.toymoban.com/news/detail-795530.html
新建EXCEL表格
文章来源地址https://www.toymoban.com/news/detail-795530.html
点击按钮读取EXCEL
代码部分
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ExcelDataReader;
namespace daoruxlsc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void LoadExcelData(string filePath)
{
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true
}
});
dataGridView1.DataSource = result.Tables[0];
}
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
LoadExcelData(filePath);
}
}
}
}
到了这里,关于C# 导出EXCEL 和 导入的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!