C#中将数据导到excel中

来源:互联网 发布:模拟笛子发音软件 编辑:程序博客网 时间:2024/04/30 08:40

需引入microsoft.office.interop

 privateMicrosoft.Office.Interop.Excel.Application myExcel = null;

 

private void ExprotExcel1()

        {

            List<Process> processes =GetExcelProcesses();

            if (processes.Count > 0)

            {

                MessageBox.Show("请关闭其他的Excel程序,以便进行导出!");

                return;

            }

            dsProducts.ProductsDataTableproductsTable = new dsProducts.ProductsDataTable();

            productsTable.AcceptChanges();

            this.Cursor = Cursors.WaitCursor;

            //保存文化环境

            System.Globalization.CultureInfoCurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;

           System.Threading.Thread.CurrentThread.CurrentCulture = newSystem.Globalization.CultureInfo("en-US");

            //保存文化环境

 

           myExcel.Application.Workbooks.Add(true);

 

            myExcel.Visible = true;

            myExcel.Cells[1, 1] ="Northwind数据库产品表";

 

            //填充标题

            for (int i = 0; i < productsTable.Columns.Count;i++)

            {

                myExcel.Cells[2, i + 1] =productsTable.Columns[i].Caption;

            }

            //填充标题

 

           dsProductsTableAdapters.ProductsTableAdapter adtProducts = newWindowsApplication1.dsProductsTableAdapters.ProductsTableAdapter();

            productsTable =adtProducts.GetProducts();

 

          

            //填充数据

            for (int i = 0; i <productsTable.Rows.Count; i++)

            {

                for (int j = 0; j <productsTable.Columns.Count; j++)

                {

                    if(productsTable.Rows[i][j].GetType() == typeof(System.String))

                    {

                        //从第3行开始

                        myExcel.Cells[i + 3, j+ 1] = "'" + productsTable.Rows[i][j].ToString();

                    }

                    else

                    {

                        //从第3行开始

                        myExcel.Cells[i + 3, j+ 1] = productsTable.Rows[i][j].ToString();

                    }

                }

            }

      

                  

            //恢复文化环境

           System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;

             this.Cursor = Cursors.Default;

            MessageBox.Show("导出成功!", "恭喜",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

        }