C# excel 常用操作

摘要:
1.Excel文件读取1.com组件操作Excel读写2.ado。net模式操作excel读写3.开源第三方组件npoi4.openxml模式读写excel模式1:使用OleDbConnectionSystem。数据DataTabledt=GetExcelDatatable(“C:用户管理员桌面技术帮助输入.xlsx”,“mapTable”

1、excel文件读取

1.  com组件操作excel 读写

2.  ado.net方式操作excel 读写

3.  开源的第三方组件npoi

4. open xml 方式读写excel

方式一使用OleDbConnection

System.Data.DataTable dt =GetExcelDatatable("C:\Users\Administrator\Desktop\技术协助录入.xlsx", "mapTable");

fileSvr.InsetData(dt);

方法体GetExcelDatatable

C# excel 常用操作第1张C# excel 常用操作第2张
/// <summary>
        /// Excel数据导入Datable
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public System.Data.DataTable GetExcelDatatable(string fileUrl, string table)
        {
            //office2007之前 仅支持.xls
            //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;
            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";

            System.Data.DataTable dt = null;
            //建立连接
            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
            try
            {
                //打开连接
                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }


                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                //获取Excel的第一个Sheet名称
                string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();

                //查询sheet中的数据
                string strSql = "select * from [" + sheetName + "]";
                OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
                DataSet ds = new DataSet();
                da.Fill(ds, table);
                dt = ds.Tables[0];

                return dt;
            }
            catch (Exception exc)
            {
                throw exc;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }

        }
View Code

方式二

C# excel 常用操作第3张C# excel 常用操作第4张
namespace _05_FileStream
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "文本文件|*.txt|所有文件|*.*";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = sfd.FileName;

                using (FileStream fs = new FileStream(txtPath.Text, FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.Write(txtLog.Text);
                    }

                    //
                    //byte[] buffer = Encoding.UTF8.GetBytes(txtLog.Text);
                    //fs.Write(buffer, 0, buffer.Length);

                    //清空缓冲,并将缓冲中的数据写入文件
                    //fs.Flush();
                    //fs.Close();

                    //fs.Dispose();
                }
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "文本文件|*.txt";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = ofd.FileName;
                using (FileStream fs = new FileStream(txtPath.Text, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs,Encoding.UTF8))
                    {
                        string msg = sr.ReadToEnd();
                        txtLog.Text = msg;
                    }
                }


                //using (FileStream fs = new FileStream(txtPath.Text,FileMode.Open))
                //{ 
                //    byte[] buffer = new byte[fs.Length];
                //    fs.Read(buffer, 0, buffer.Length);
                //    string msg = Encoding.UTF8.GetString(buffer,0,buffer.Length);
                //    txtLog.Text = msg;
                //}
            }
        }
    }
}
View Code

2、excel文件导出

3、文档下载 

C# excel 常用操作第5张C# excel 常用操作第6张
/// <summary>
        /// 征信材料
        /// </summary>
        /// <param name="fileName"></param>
        public void DownLoad(string fileName = "金融交易平台-搜房金融管理后台使用说明V1.1.pdf")
        {
            string browser = Request.UserAgent.ToUpper();
            FileStream filestream = new FileStream(Server.MapPath("/Manager/Attach/" + fileName), FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            long filesize = filestream.Length;
            //让客户端浏览器正确识别这个文件的类型和文件大小
            System.IO.Path.GetFileName(Server.MapPath("/Manager/Attach/" + fileName)).ToLower();
            Response.ContentType = "application/octet-stream";
            if (browser.Contains("FIREFOX") == true)
            {
                fileName = fileName;
            }
            else
            {
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);

            }
            Response.AddHeader("Content-Disposition", "attachment; filename="" + fileName + "";");
            Response.AddHeader("Content-Length", filesize.ToString());
            //将文件中的数据发送到客户端
            byte[] filebuffer = new byte[filesize];
            filestream.Read(filebuffer, 0, (int)filesize);
            Response.BinaryWrite(filebuffer);

            filestream.Close();
            Response.End();
        }
View Code

 MVC

public FileResult SubjectExcel()
{
IEnumerable<SubjectExcel> listExcel = ServiceFactory.GetService<ISubjectService>().GetSubjectExcel((int)(base.ProductEnum));
new NPOIHelper().Export<SubjectExcel>(listExcel, "", Server.MapPath("~/题目导入模板/标准科目参考.xlsx"));
return File(Server.MapPath("~/题目导入模板/标准科目参考.xlsx"), "application/ms-excel", "标准科目参考.xls");
}

免责声明:文章转载自《C# excel 常用操作》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Python数据分析丨numpy基本操作,了解一下?卫星地面站的天线下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

token解决前后端分离认证和跨域问题和JWT的使用

二、使用token解决前端后端分离用户认证问题 2.1 用户提交帐号和密码到服务器的认证接口 login.html doSubmit:function(){ console.log("~~~~~~~~~~~~~doSubmit"); axios.get("http://localhost:8080/user/login",{...

Go 字符串拼接6种,最快的方式 strings.builder

我们首先来了解一下Go语言中string类型的结构定义,先来看一下官方定义: // string is the set of all strings of 8-bit bytes, conventionally but not// necessarily representing UTF-8-encoded text. A string may be em...

springMVC使用map接收入参 + mybatis使用map 传入查询参数

 测试例子: controllel层 ,使用map接收请求参数,通过Debug可以看到,请求中的参数的值都是字符串形式,如果将这个接收参数的map直接传入service,mybatis接收参数时会报错,因此要先对请求中的参数进行预处理 1 package org.slsale.test; 2 3 import java.util.Date; 4...

在lua的string库和正则表达式

一.前提要了解一下lua 的string几个方法 1. string库中所有的字符索引从前往后是1,2,...;从后往前是-1,-2,... 2. string库中所有的function都不会直接操作字符串,而是返回一个结果 string.len(s):返回字符串的长度. string.lower(s):变小写. string.upper(s):变大写....

.NET插件系统

面临的问题       在开发插件系统中,我们通常会面临这样的问题:        一些功能并不是在开启时就要被使用的,例如VS中的大量功能对一个大部分程序员来说用不着,但框架本身却应该向用户提供该插件的相应信息?        在可视化的插件功能列表中,我们不仅希望提供简单的插件名称信息,更希望能以图片,或动画等形式展示其功能特性,便于用户选择。   ...

整理分布式锁:业务场景&amp;amp;分布式锁家族&amp;amp;实现原理

1、引入业务场景 业务场景一出现: 因为小T刚接手项目,正在吭哧吭哧对熟悉着代码、部署架构。在看代码过程中发现,下单这块代码可能会出现问题,这可是分布式部署的,如果多个用户同时购买同一个商品,就可能导致商品出现库存超卖 (数据不一致)现象,对于这种情况代码中并没有做任何控制。 原来一问才知道,以前他们都是售卖的虚拟商品,没啥库存一说,所以当时没有考虑那么多...