博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 操作Excel文件的方法
阅读量:5064 次
发布时间:2019-06-12

本文共 16248 字,大约阅读时间需要 54 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using System.Data;using System.Windows.Forms;using System.IO;using System.Data.OleDb;using System.Collections;//////使用该类 需要添加 NOPI.dll 的引用///版本为 2.0.0.0 namespace CommonClass{    public static class ExcelHelper    {        #region  导出        ///         /// 导出一个Datatable的数据到Excel文件        ///         /// 需要导出的DataTable        public static void ExportDataTableToExcel(DataTable dt)        {            try            {                HSSFWorkbook wk = new HSSFWorkbook();                ISheet sheet = wk.CreateSheet("Sheet1");                int RowCount = dt.Rows.Count;                int ColumnCount = dt.Columns.Count;                IRow row = sheet.CreateRow(0);                for (int j = 0; j < ColumnCount; j++) //列标题                {                    sheet.SetColumnWidth(j, 20 * 256);                    ICell cell = row.CreateCell(j);                    cell.SetCellType(CellType.STRING);                    cell.SetCellValue(dt.Columns[j].ColumnName);                }                for (int i = 0; i < RowCount; i++)                {                    row = sheet.CreateRow(i + 1);                    for (int j = 0; j < ColumnCount; j++)                    {                        sheet.SetColumnWidth(j, 20 * 256);                        ICell cell = row.CreateCell(j);                        cell.SetCellType(CellType.STRING);                        cell.SetCellValue(dt.Rows[i][j].ToString());                    }                }                SaveFileDialog dlg = new SaveFileDialog();                dlg.Filter = "Execl files (*.xls)|*.xls";                dlg.FilterIndex = 0;                dlg.RestoreDirectory = true;                dlg.CreatePrompt = true;                dlg.Title = "保存为Excel文件";                if (dlg.ShowDialog() == DialogResult.OK)                {                    using (FileStream fs = File.OpenWrite(dlg.FileName)) //打开一个xls文件,如果没有则自行创建,如果存在文件则在创建是不要打开该文件!                    {                        wk.Write(fs);   //向打开的这个xls文件中写入Sheet1表并保存。                        MessageBox.Show("导出成功!");                    }                }            }            catch (Exception ex)            {                MessageBox.Show(ex.Message);            }        }        ///         /// 导出一个DataGridView的数据到Excel文件        ///         /// 绑定了数据源的DataGridView控件        public static void ExportDataGridViewToExcel(DataGridView Gridview)        {            HSSFWorkbook wk = new HSSFWorkbook();            ISheet sheet = wk.CreateSheet("Sheet1");            int RowCount = Gridview.RowCount;            int ColumnCount = Gridview.ColumnCount;            IRow row = sheet.CreateRow(0);            for (int j = 0; j < ColumnCount; j++) //列标题            {                sheet.SetColumnWidth(j, 20 * 256);                ICell cell = row.CreateCell(j);                cell.SetCellType(CellType.STRING);                cell.SetCellValue(Gridview.Columns[j].HeaderText);            }            for (int i = 0; i < RowCount; i++)            {                row = sheet.CreateRow(i + 1);                for (int j = 0; j < ColumnCount; j++)                {                    sheet.SetColumnWidth(j, 20 * 256);                    ICell cell = row.CreateCell(j);                    cell.SetCellType(CellType.STRING);                    cell.SetCellValue(Gridview.Rows[i].Cells[j].Value.ToString());                }            }            SaveFileDialog dlg = new SaveFileDialog();            dlg.Filter = "Execl files (*.xls)|*.xls";            dlg.FilterIndex = 0;            dlg.RestoreDirectory = true;            dlg.CreatePrompt = true;            dlg.Title = "保存为Excel文件";            if (dlg.ShowDialog() == DialogResult.OK)            {                using (FileStream fs = File.OpenWrite(dlg.FileName)) //打开一个xls文件,如果没有则自行创建,如果存在文件则在创建是不要打开该文件!                {                    wk.Write(fs);   //向打开的这个xls文件中写入Sheet1表并保存。                    MessageBox.Show("导出成功!");                }            }        }        #endregion        #region 读取        ///         /// 读取一个Excel文件(只读取该文件的第一个Sheet的数据)        ///         /// 
返回一个包含Excel文件数据的DataTable
public static DataTable ReadExcelToDataTable() { DataTable dt = new DataTable(); OpenFileDialog OpenDialog = new OpenFileDialog(); OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; OpenDialog.Title = "读取Excel文件"; OleDbConnection con; OleDbDataAdapter da; DataSet ds = new DataSet(); if (OpenDialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OpenDialog.FileName)) { MessageBox.Show("请选择Excel文件!"); return dt; } else { try { string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.')); string connStr = ""; switch (filename) { case ".xls": { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } case ".xlsx": { connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } default: { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } } string sql = "SELECT * FROM [" + GetExcelFirstTableName(OpenDialog.FileName, connStr)[0].ToString() + "] "; con = new OleDbConnection(connStr); con.Open(); da = new OleDbDataAdapter(sql, con); da.Fill(ds); if (ds.Tables[0].Rows.Count == 0) { MessageBox.Show("选择的文件没数据!"); return dt; } else { dt = ds.Tables[0]; } return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); return dt; } } } return dt; } /// /// 读取一个Excel文件(读取该文件的所有Sheet的数据,但是该文件的所有Sheet数据格式必须一致) /// ///
返回一个包含Excel文件数据的DataTable
public static DataTable ReadMoreExcelToDataTable() { DataTable dt = new DataTable(); OpenFileDialog OpenDialog = new OpenFileDialog(); OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; OpenDialog.Title = "读取Excel文件"; OleDbConnection con; OleDbDataAdapter da; DataSet ds = new DataSet(); if (OpenDialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OpenDialog.FileName)) { MessageBox.Show("请选择Excel文件!"); return dt; } else { try { string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.')); string connStr = ""; switch (filename) { case ".xls": { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } case ".xlsx": { connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } default: { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } } ArrayList sqllist = new ArrayList(); ArrayList tablelist = new ArrayList(); tablelist = GetExcelAllTableName(OpenDialog.FileName, connStr); for (int i = 0; i < tablelist.Count; i++) { sqllist.Add("SELECT * FROM [" + tablelist[i] + "]"); } con = new OleDbConnection(connStr); con.Open(); for (int i = 0; i < sqllist.Count; i++) { da = new OleDbDataAdapter(sqllist[i].ToString(), con); da.Fill(ds); } if (ds.Tables[0].Rows.Count == 0) { MessageBox.Show("选择的文件没数据!"); return dt; } else { dt = ds.Tables[0]; } return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); return dt; } } } return dt; } /// /// 读取一个Excel文件(读取该文件的所有Sheet的数据,该文件的Sheet数据格式可以一致) /// ///
返回一个包含Excel文件数据的DataSet
public static DataSet ReadMoreNotSameExcelToDataTable() { DataTable dt = new DataTable(); OpenFileDialog OpenDialog = new OpenFileDialog(); OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; OpenDialog.Title = "读取Excel文件"; OleDbConnection con; OleDbDataAdapter da; DataSet ds = new DataSet(); if (OpenDialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OpenDialog.FileName)) { MessageBox.Show("请选择Excel文件!"); return ds; } else { try { string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.')); string connStr = ""; switch (filename) { case ".xls": { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } case ".xlsx": { connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } default: { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } } ArrayList sqllist = new ArrayList(); ArrayList tablelist = new ArrayList(); tablelist = GetExcelAllTableName(OpenDialog.FileName, connStr); for (int i = 0; i < tablelist.Count; i++) { sqllist.Add("SELECT * FROM [" + tablelist[i] + "]"); } con = new OleDbConnection(connStr); con.Open(); for (int i = 0; i < sqllist.Count; i++) { da = new OleDbDataAdapter(sqllist[i].ToString(), con); da.Fill(ds, "Table" + i); } bool isHave = false; for (int i = 0; i < ds.Tables.Count; i++) { if (ds.Tables[i].Rows.Count != 0) { isHave = true; } } if (!isHave) { MessageBox.Show("选择的文件没数据!"); return ds; } return ds; } catch (Exception ex) { MessageBox.Show(ex.Message); return ds; } } } return ds; } /// /// 获取第一个Sheet的名称 /// /// Excel文件名称 /// 读取Excel文件数据的数据连接 ///
private static ArrayList GetExcelFirstTableName(string excelFileName, string strExtension) { ArrayList tablenamelist = new ArrayList(); try { if (File.Exists(excelFileName)) { using (OleDbConnection conn = new OleDbConnection(strExtension)) { conn.Open(); DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); tablenamelist.Add(dt.Rows[0][2].ToString().Trim()); return tablenamelist; } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return tablenamelist; } /// /// 获取所有Sheet的名称 /// /// Excel文件名称 /// 读取Excel文件数据的数据连接 ///
private static ArrayList GetExcelAllTableName(string excelFileName, string strExtension) { ArrayList tablenamelist = new ArrayList(); try { if (File.Exists(excelFileName)) { using (OleDbConnection conn = new OleDbConnection(strExtension)) { conn.Open(); DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); for (int i = 0; i < dt.Rows.Count; i++) { tablenamelist.Add(dt.Rows[i][2].ToString().Trim()); } return tablenamelist; } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return tablenamelist; } #endregion }}

 

转载于:https://www.cnblogs.com/ShuiMu/articles/3497841.html

你可能感兴趣的文章
SpringMVC中JSP取不到ModelAndView的数据原因
查看>>
cenos 安装 phpredis 扩展
查看>>
Yii2 的 redis 应用
查看>>
sqlplus登陆
查看>>
HDU1814 2-sat 模板
查看>>
IDEA连接数据库自动生成实体类
查看>>
linux 用户管理
查看>>
分享接口
查看>>
团队作业-Beta冲刺(周三)
查看>>
javascript有用小功能总结(未完待续)
查看>>
(Problem 3)Largest prime factor
查看>>
【SQL】表A多个字段,关联表B一个字段说明
查看>>
python网络编程
查看>>
单例双重加锁
查看>>
[翻译svg教程]svg中的circle元素
查看>>
HDU 1201 Fibonacci Again
查看>>
ASP.NET MVC视图和控制器之间的传值总结(一)
查看>>
敏捷与 DevOps:是敌是友?
查看>>
bzoj1588营业额统计
查看>>
概率与数学期望
查看>>