现在的位置: 首页 > 综合 > 正文

Excel文件导入导出类

2013年11月08日 ⁄ 综合 ⁄ 共 12265字 ⁄ 字号 评论关闭

/// <summary>
    /// Excel文件导入导出类
    /// 需引用Microsoft Excel 11.0 Object Library
    /// </summary>
    public class ExcelIO
    {
        private static System.Windows.Forms.DataGridView gridView;
        private static System.Windows.Forms.ToolStripProgressBar  toolStripProgressBar1;
        private static Timer time;
        private static DataSet objSet = new DataSet();
        private static DataSet outSet = new DataSet();
        private static SaveFileDialog saveFileDialog = new SaveFileDialog();
        private static SaveFileDialog saveFileDialog2 = new SaveFileDialog();
        private static OpenFileDialog openFileDialog = new OpenFileDialog();

        public static System.Windows.Forms.DataGridView _gridView
        {
            get { return gridView; }
            set { gridView = value;}
        }
        public static System.Windows.Forms.ToolStripProgressBar _toolStripProgressBar1
        {
            get { return toolStripProgressBar1; }
            set { toolStripProgressBar1 = value;}
        }
        /// <summary>
        /// 打开窗口选中的文件地址
        /// </summary>
        public static string FileName
        {
            get { return openFileDialog.FileName; }
        }
        public static Timer _time
        {
            get { return time; }
            set { time = value;}
        }
        public static DataSet _objSet
        {
            get { return objSet; }
            set { objSet.Clear(); objSet = value; }
        }
        public static DataSet _outSet
        {
            get { return outSet; }
            set { outSet.Clear(); outSet = value; }
        }

        /// <summary>
        /// 导入EXCEL到DataSet
        /// </summary>
        public static void ImportExcel()
        {
            openFileDialog.Filter = "Execl files (*.xls)|*.xls";
            openFileDialog.FilterIndex = 0;
            openFileDialog.RestoreDirectory = true;
            openFileDialog.Title = "导入文件保存路径";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string strName = openFileDialog.FileName;
                toolStripProgressBar1.Visible = true;
                System.Reflection.Missing miss = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                if (excel == null)
                {
                    MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Microsoft.Office.Interop.Excel.Workbook workbook;
                try
                {
                    workbook = excel.Workbooks.Open(strName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                        "", true, false, 0, true, 1, 0);
                }
                catch
                {
                    MessageBox.Show("Excel文件处于打开状态,请保存关闭!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //获得所有Sheet名称
                int n = workbook.Worksheets.Count;
                string[] SheetSet = new string[n];
                System.Collections.ArrayList al = new System.Collections.ArrayList();
                for (int i = 1; i <= n; i++)
                {
                    SheetSet[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i]).Name;
                }

                //释放Excel相关对象
                workbook.Close(null, null, null);
                excel.Quit();
                if (workbook != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    workbook = null;
                }
                if (excel != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                    excel = null;
                }
                GC.Collect();

                //把EXCEL导入到DataSet
                DataSet ds = new DataSet();
                string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + strName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                using (OleDbConnection conn = new OleDbConnection(connStr))
                {
                    conn.Open();
                    OleDbDataAdapter da;
                    for (int i = 1; i <= n; i++)
                    {
                        string sql = "select * from [" + SheetSet[i - 1] + "$] ";
                        da = new OleDbDataAdapter(sql, conn);
                        da.Fill(ds, SheetSet[i - 1]);
                        da.Dispose();
                        toolStripProgressBar1.Value += 100 / n;
                    }
                    conn.Close();
                    conn.Dispose();
                }
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Visible = false;
                outSet = ds;
            }
            else
            {
                openFileDialog.FileName = "";
            }
        }

        /// <summary>
        /// 导出当前页DataGridView中的数据到EXcel中
        /// </summary>
        public static void ExportTOExcel()
        {
            if (gridView.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "导出文件保存路径";
                saveFileDialog.ShowDialog();
                string strName = saveFileDialog.FileName;
                if (strName.Length != 0)
                {
                    toolStripProgressBar1.Visible = true;
                    System.Reflection.Missing miss = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    excel.Application.Workbooks.Add(true); ;
                    excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
                    if (excel == null)
                    {
                        MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
                    Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
                    sheet.Name = "test";

                    //生成字段名称
                    for (int i = 0; i < gridView.ColumnCount; i++)
                    {
                        excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText.ToString();
                    }
                    //填充数据
                    int rowc = gridView.RowCount;
                    if (!gridView.ColumnHeadersVisible)
                    {
                        rowc -= 1;
                    }
                    for (int i = 0; i < rowc; i++)
                    {
                        for (int j = 0; j < gridView.ColumnCount; j++)
                        {
                            if (gridView[j, i].Value == typeof(string))
                            {
                                excel.Cells[i + 2, j + 1] = "" + gridView[i, j].Value.ToString();
                            }
                            else
                            {
                                excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
                            }
                        }
                        toolStripProgressBar1.Value += 100 / gridView.RowCount;
                    }
                    sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                    book.Close(false, miss, miss);
                    books.Close();
                    excel.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                    GC.Collect();
                    MessageBox.Show("数据已经成功导出到:" + saveFileDialog.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    toolStripProgressBar1.Value = 0;
                    toolStripProgressBar1.Visible = false;
                }
            }
        }

        //-------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 导出整个DataGridView中的数据到Excel中
        /// </summary>
        public static void ExportTOExcel2()
        {
            if (gridView.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                saveFileDialog2.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog2.FilterIndex = 0;
                saveFileDialog2.RestoreDirectory = true;
                //saveFileDialog2.CreatePrompt = true;
                saveFileDialog2.Title = "导出文件保存路径";
                saveFileDialog2.FileName = null;
                saveFileDialog2.ShowDialog();
                string FileName =  saveFileDialog2.FileName;

                if (FileName.Length != 0)
                {
                    toolStripProgressBar1.Visible = true;
                    System.Data.DataTable dt = objSet.Tables[0];

                    FileStream objFileStream;
                    StreamWriter objStreamWriter;
                    string strLine = "";
                    objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                    objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
                    toolStripProgressBar1.Value = 0;

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        strLine = strLine + dt.Columns[i].ColumnName.ToString() + Convert.ToChar(9);

                    }
                    objStreamWriter.WriteLine(strLine);
                    strLine = "";

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        strLine = strLine + (i + 1) + Convert.ToChar(9);
                        for (int j = 1; j < dt.Columns.Count; j++)
                        {
                            strLine = strLine + dt.Rows[i][j].ToString() + Convert.ToChar(9);

                        }
                        objStreamWriter.WriteLine(strLine);
                        toolStripProgressBar1.Value += 100 / dt.Rows.Count;
                        strLine = "";
                    }
                    objStreamWriter.Close();
                    objFileStream.Close();
                    MessageBox.Show("数据已经成功导出到:" + saveFileDialog2.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    toolStripProgressBar1.Value = 0;
                    toolStripProgressBar1.Visible = false;
                }
            }
        }

        //————————————————————————————————————————————————————————————————————
        /// <summary>
        /// 导出到XML(整个数据源)
        /// </summary>
        public static void ExportTOXML()
        {
            if (gridView.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                saveFileDialog2.Filter = "XML files (*.xml)|*.xml";
                saveFileDialog2.FilterIndex = 0;
                saveFileDialog2.RestoreDirectory = true;
                //saveFileDialog2.CreatePrompt = true;
                saveFileDialog2.Title = "导出文件保存路径";
                saveFileDialog2.FileName = null;
                saveFileDialog2.ShowDialog();
                string FileName =  saveFileDialog2.FileName;

                if (FileName.Length != 0)
                {
                    toolStripProgressBar1.Visible = true;
                    objSet.WriteXml(saveFileDialog2.FileName.ToString());
                    for (int i = 0; i < objSet.Tables[0].Rows.Count; i++)
                    {
                        toolStripProgressBar1.Value += 100 / objSet.Tables[0].Rows.Count;
                    }
                    MessageBox.Show("数据已经成功导出到:" + saveFileDialog2.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    toolStripProgressBar1.Value = 0;
                    toolStripProgressBar1.Visible = false;
                }
            }
        }
    }

抱歉!评论已关闭.