Idealist

  博客园  ::  :: 新随笔  ::  :: 订阅 订阅  :: 管理
  20 随笔 :: 0 文章 :: 17 评论

本次阐述的导入和导出都围绕此Demo进行

1.导入Excel文件到Gridview

首先列出导入Excel文件需要添加的Using:

  1>Using System.IO;

  2>Using System.Data.OleDb;

主要用到的对象(类):

  1>OpenFileDialog

  2>FileInfo

  3>DataTabel

  4>OleDb

具体代码如下:

 public DataTable Import()
        {
            OpenFileDialog oFD = new OpenFileDialog();
            oFD.Filter = "Execl files (*.xls)|*.xls";
            oFD.FilterIndex = 0;
            oFD.RestoreDirectory = true;
            oFD.Title = "将Excel文件数据导入到DataSet";
            oFD.ShowDialog();
            string fileName = oFD.FileName;
            FileInfo file = new FileInfo(fileName);
            if (!file.Exists)
            {
                throw new Exception("文件不存在");
            } string extension = file.Extension;
            string strConn = "";
            switch (extension)
            {
                case ".xls":
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
                    break;
                case ".xlsx":
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    break;
                default:
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
            }
            DataTable dt = new DataTable();
            OleDbConnection oleConn = new OleDbConnection(strConn);
            oleConn.Open();

            DataTable dtSheetName = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
            string[] strTableNames = new string[dtSheetName.Rows.Count];

            //得到选中文件中Sheet的表名
            for (int k = 0; k < dtSheetName.Rows.Count; k++)
            {
                strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
            }
            //默认只读取第一张(根据需求更改查询语句)
            string strSql = "select * FROM [" + strTableNames[0] + "]";
            OleDbCommand oleCom = new OleDbCommand(strSql, oleConn);
            using (OleDbDataReader rdr = oleCom.ExecuteReader())
            {
                dt.Load(rdr);
            }
            oleConn.Close();
            return dt;
        }

经过测试,简单的导入是没有问题的,不过更深层的导入需要大家再做修改。

 

 

2.导出Gridview数据到Excel文件

首先列出导出Excel文件需要添加的Using:

  1>Using System.IO;

主要用到的对象(类):

  1>SaveFileDialog

  2>Stream

  3>StreamWriter

具体代码如下:

public void Out(DataGridView dgv)
        {
            SaveFileDialog sFD = new SaveFileDialog();
            sFD.Filter = "Excel Files(*.xls)|*.xls";
            sFD.FilterIndex = 0;
            sFD.RestoreDirectory = true;
            sFD.CreatePrompt = true;//如果文件不存在,提示创建
            sFD.Title = "保存为Excel文件!";
            if (sFD.ShowDialog() == DialogResult.OK)
            {
                Stream saveStream = sFD.OpenFile();//打开要保存的excel文件 
                StreamWriter sw = new StreamWriter(saveStream, Encoding.GetEncoding(-0));//以特定的编码向流中插入字符,
                //GetEncoding(-0) 
                //首选编码的代码页标识符。- 或 - 0 
                string columnTitle = "";
                try
                {
                    for (int i = 0; i < dgv.ColumnCount; i++)
                    {
                        if (i > 0)
                            columnTitle += "\t";
                        columnTitle += dgv.Columns[i].HeaderText;
                    }
                    sw.WriteLine(columnTitle);//写入标题行 
                    for (int j = 0; j < dgv.RowCount; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < dgv.ColumnCount; k++)
                        {
                            if (k > 0)
                                columnValue += "\t";
                            if (dgv.Rows[j].Cells[k].Value.ToString() == "")
                            {
                                columnValue += "";
                            }
                            else
                                columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                        }
                        sw.WriteLine(columnValue);//将信息逐条的写入excel文件 
                    }
                    sw.Close();
                    saveStream.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

导出后结果:

由此实现了简单的数据导出到Excel文件中

posted on 2014-01-21 11:09  seaconch  阅读(1521)  评论(1编辑  收藏