• 将DataTable中的数据导出成Excel


    public bool ExportFile(System.Data.DataTable dt)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
        sfd.Title = "Excel文件导出";
        string fileName = "";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            fileName = sfd.FileName;
            Excel.Application app = new Excel.Application();
            if (app == null)
            {
                MessageBox.Show("Excel启动失败!");
                return false;
            }
            try
            {
                app.Visible = false;
                Excel.Workbook xlWorkBook = app.Workbooks.Add(Type.Missing);
                Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                int i;
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
                }
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        string tt = dt.Rows[i][j].ToString();
                        xlWorkSheet.Cells[i + 2, j + 1] = tt;
                    }
                }
                xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                xlWorkBook.Close(true, Type.Missing, Type.Missing);
                app.Quit();                   
                       
                xlWorkSheet = null;
                xlWorkBook = null;

                return true;
            }
            catch (System.Exception exc)
            {
                MessageBox.Show("excel运行错误:" + exc.Message);
                return false;
            }
        }
        else
        {
            return false;
        }
    }

  • 相关阅读:
    随时查询
    插入图片后R文件变红,报错“Error::app:mergeDebugResources'. > Some file crunching failed, see logs for detail”
    android 布局
    用SVN导入android项目时候没有导入default.properties这文件的解决方法
    Button的点击事件可以在XML文件中设置
    设置全屏有两种方式
    android 中加入的音乐文件有的时候没有播放。
    android spinner 调用xml里的数据
    刚刚申请了个博客发发感想
    .Net下WinForm换肤控件整理(转)
  • 原文地址:https://www.cnblogs.com/pnljs/p/3160765.html
Copyright © 2020-2023  润新知