C# 导出EXCEL 和 导入

本文介绍了如何使用C#在WindowsForm应用中通过Excel.Application接口实现数据导出到XLSX文件,以及使用ExcelDataReader库处理Excel文件并加载至DataGridView。
摘要由CSDN通过智能技术生成

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依赖项

在这里插入图片描述
在这里插入图片描述

新建EXCEL表格

在这里插入图片描述

点击按钮读取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);
            }
        }
    }
}

/// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <returns></returns> public bool ToExcel(DataTable table) { FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); IWorkbook workBook = new HSSFWorkbook(); this._sheetName = this._sheetName.IsEmpty() ? "sheet1" : this._sheetName; ISheet sheet = workBook.CreateSheet(this._sheetName); //处理表格标题 IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue(this._title); sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1)); row.Height = 500; ICellStyle cellStyle = workBook.CreateCellStyle(); IFont font = workBook.CreateFont(); font.FontName = "微软雅黑"; font.FontHeightInPoints = 17; cellStyle.SetFont(font); cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.Alignment = HorizontalAlignment.Center; row.Cells[0].CellStyle = cellStyle; //处理表格列头 row = sheet.CreateRow(1); for (int i = 0; i < table.Columns.Count; i++) { row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName); row.Height = 350; sheet.AutoSizeColumn(i); } //处理数据内容 for (int i = 0; i < table.Rows.Count; i++) { row = sheet.CreateRow(2 + i); row.Height = 250; for (int j = 0; j < table.Columns.Count; j++) { row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString()); sheet.SetColumnWidth(j, 256 * 15); } } //写入数据流 workBook.Write(fs); fs.Flush(); fs.Close(); return true; } /// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <param name="title"></param> /// <param name="sheetName"></param> /// <returns></returns> public bool ToExcel(DataTable table, string title, string sheetName, string filePath) { this._title = title; this._sheetName = sheetName; this._filePath = filePath; return ToExcel(table); }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值