博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#导入导出(excel)数据
阅读量:4975 次
发布时间:2019-06-12

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

今天弄了一个导入导出excel数据的例子,首先命名空间要引用:Microsoft.Office.Interop.Excel和System.IO。下面是我弄的代码(仅限参考):

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.IO;
namespace ImportExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Data.DataTable dt = new System.Data.DataTable();
        //将excel里的数据导入数据到windows窗体
        private void btn_Import_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Excel Files|*.xls";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string filename = ofd.FileName;
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook workbook;
                Microsoft.Office.Interop.Excel.Worksheet worksheet;
                object oMissing = System.Reflection.Missing.Value;
                workbook = excel.Workbooks.Open(filename, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
                worksheet = (Worksheet)workbook.Worksheets[1];
                int rowCount = worksheet.UsedRange.Rows.Count;
                int colCount = worksheet.UsedRange.Columns.Count;
                Microsoft.Office.Interop.Excel.Range range1;
                
                int i;
                for (i = 0; i < colCount; i++)
                {
                    range1 = worksheet.Range[worksheet.Cells[1, i + 1], worksheet.Cells[1, i + 1]];
                    dt.Columns.Add(range1.Value2.ToString());
                }
                int j;
                for (j = 1; j < rowCount; j++)
                {
                    DataRow dr = dt.NewRow();
                    for (i = 0; i < colCount; i++)
                    {
                        range1 = worksheet.Range[worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]];
                        dr[i] = range1.Value2;
                    }
                    dt.Rows.Add(dr);
                }
                dgv_Import.DataSource = dt;
                excel.Quit();
            }
            else
            {
                MessageBox.Show("文件路径出错!");
            }
        }
        //将刚导入windows窗体的数据保存到对应的数据库中
        private void btn_Save_Click(object sender, EventArgs e)
        {
            string connStr = "server=.;database=SDSYSTEM;Trusted_Connection=true";
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(connStr,conn);
            cmd.CommandText = "insert into Student (studentId,studentName,sex,academyId,majorId,dormId,memo) values (@学号,@姓名,@性别,@学院,@专业,@宿舍,@备注)";
            cmd.Parameters.Add(new SqlParameter("@学号", SqlDbType.VarChar));
            cmd.Parameters.Add(new SqlParameter("@姓名", SqlDbType.VarChar));
            cmd.Parameters.Add(new SqlParameter("@性别", SqlDbType.VarChar));
            cmd.Parameters.Add(new SqlParameter("@学院", SqlDbType.VarChar));
            cmd.Parameters.Add(new SqlParameter("@专业", SqlDbType.VarChar));
            cmd.Parameters.Add(new SqlParameter("@宿舍", SqlDbType.VarChar));
            cmd.Parameters.Add(new SqlParameter("@备注", SqlDbType.VarChar));
            if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cmd.Parameters["@学号"].Value = dt.Rows[i][0].ToString();
                    cmd.Parameters["@姓名"].Value = dt.Rows[i][1].ToString();
                    cmd.Parameters["@性别"].Value = dt.Rows[i][2].ToString();
                    cmd.Parameters["@学院"].Value = dt.Rows[i][3].ToString();
                    cmd.Parameters["@专业"].Value = dt.Rows[i][4].ToString();
                    cmd.Parameters["@宿舍"].Value = dt.Rows[i][5].ToString();
                    cmd.Parameters["@备注"].Value = dt.Rows[i][6].ToString();
                    cmd.ExecuteNonQuery();  //每一次都要执行一次插入操作,而不能讲插入操作放在for外面
                }
                conn.Close();
                MessageBox.Show("成功将数据保存到数据库中!");
                dgv_Import.DataSource = null;
                dgv_Import.ReadOnly = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存数据有错!" + ex.Message.ToString());
            }
        }
        //将windows里的数据导出到excel里
        private void btn_OutPut_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();   //实例化一个SaveFileDialog保存文件对话框
            dlg.Filter = "Excel files (*.xls)|*.xls";
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string columnTitle = "";
                try
                {
                    //写入列标题
                    for (int i = 0; i < dgv_Import.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            columnTitle += "\t";
                        }
                        columnTitle += dgv_Import.Columns[i].HeaderText;
                    }
                    sw.WriteLine(columnTitle);
                    //写入列内容
                    for (int j = 0; j < dgv_Import.Rows.Count; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < dgv_Import.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                columnValue += "\t";
                            }
                            if (dgv_Import.Rows[j].Cells[k].Value == null)
                                columnValue += "";
                            else
                                columnValue += dgv_Import.Rows[j].Cells[k].Value.ToString().Trim();
                        }
                        sw.WriteLine(columnValue);
                    }
                    sw.Close();
                    myStream.Close();
                }
                catch
                {
                    MessageBox.Show("导出不成功");
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
    }
}

转载于:https://www.cnblogs.com/WSL-william-love/archive/2012/04/23/2466685.html

你可能感兴趣的文章
js 浏览器复制功能
查看>>
数据库总编
查看>>
redis 字符串(string)函数
查看>>
杭州电 1372 Knight Moves(全站搜索模板称号)
查看>>
POJ--3268--Silver Cow Party【SPFA+邻接表】
查看>>
c语言的几个简单memo
查看>>
C#的默认访问权限
查看>>
selenium下打开Chrome报错解决
查看>>
红酒初识
查看>>
BNUOJ 5629 胜利大逃亡(续)
查看>>
HDU-1150 Machine Schedule(二分图、匈牙利)
查看>>
Python assert 断言函数
查看>>
修改 CKEditor 超链接的默认协议
查看>>
zoj3795 Grouping --- 良好的沟通,寻找最长的公路
查看>>
【SSH2(理论+实践)】--Hibernate步步(一个)
查看>>
bzoj3156 防御准备
查看>>
Eclipse修改编码格式
查看>>
生成器和协程 —— 你想知道的都在这里了
查看>>
初级算法-6.两个数组的交集 II
查看>>
欧拉函数 / 蒙哥马利快速幂 / 容斥
查看>>