zoukankan      html  css  js  c++  java
  • 私人笔记 C#导出Excel

    using System.IO;
             
    /// <summary>
            /// Get the save file full name
            /// </summary>
            /// <remarks>
            /// If the file exist, then delete the file.
            /// </remarks>
            /// <param name="fileName">save file full name, If null then open dialog to select and input save file name</param>
            /// <param name="fileSuffix">file Suffix,ex:"xls"</param>
            /// <param name="fileFilter">file filter defination ,ex:"EXCEL(*.xls)|*.xls"</param>
            /// <returns>except or cancel dialog return empty string, else return save file full name</returns>
    public static string GetSaveFileName(string fileName,string fileSuffix,string fileFilter)
    {
        string saveFileNameString = string.Empty;
        try
        {
            if(fileName == null || fileName.Trim() == "")
            {
                //声明保存对话框
                SaveFileDiaLog dlg = new SaveFileDialog();
                //默认文件后缀
                dlg.DefaultExt = fileSuffix;
                //文件后缀列表
                dlg.Filter = fileFilter;
                //默认路径是系统当前路径
                dlg.InitialDirectory = Directory.GetCurrentDirectory();
                //打开保存对话框
                if (dlg.ShowDialog() == DialogResult.Cancel) return "";
                //返回文件路径
                saveFileNameString = dlg.FileName;
            }
            else
                saveFileNameString = fileName;
    
            if (saveFileNameString.Trim() == "")
                return "";
            //验证以fileNameString命名的文件是否存在,如果存在删除它
            FileInfo file = new FileInfo (saveFileNameString);
            if(file.Exists)
            {
                try
                {
                    file.Delete();
                }
                catch (Exception error)
                {
                    AppMessageBox.ShowErrorNoTranslate(error.Message);
                    return "";
                }
            }
            return saveFileNameString;
        }
        catch
        {
            return "";
        }
    }       
    
    
    public void CreateToExcel(string fileName)
    {
        string fileNameString = GetSaveFileName(fileName, "xls", "EXCEL(*.xls)|*.xls");
         //验证strFileName 是否为空或无效 
        if (fileNameString.Trim() == "")
            return;
    
        //定义表格内数据的行数和列数
    
        Microsoft.Office.Interop.Excel.Application objExcel = null;
    
        Workbook objWorkbook = null;  //excel 工作簿
        Worksheet objsheet = null; //excel sheet页
        try
        {
            //声明对象
            objExcel = new Microsoft.Office.Interop.Excel.Application();
            CultureInfo oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
            CultureInfo newCulture = new CultureInfo(objExcel.LanguageSettings.get_languageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanfuageIDUI));
            System.Threading.Thread.CurrentThread.CurrentCulture = new newCulture;
            //声明excel工作簿
            objWorkbook = objExcel.Workbooks.Add(Missing.Value);
            //声明sheet页
            objsheet = (Worksheet)objWorkbook.ActiveSheet;     
            //页面设置
            objsheet.PageSetup.PagerSize = XlPagerSize.xlPagerA4; //设置A4格式
            objsheet.PageSetup.BottomMargin = 0.5 / 0.035;
            objsheet.PageSetup.TopMargin = 2 / 0.035;
            objsheet.PageSetup.LeftMargin = 0.1 / 0.035;
            objsheet.PageSetup.RightMargin = 0.05 / 0.035;
    
            objsheet.PageSetup.Zoom = 90;
            objsheet.PageSetup.CenterHorizontally = true;
    
            string position = string.Empty;
            //设置EXCEL是否可见
            objExcel.Visible = false;
            Microsoft.Office.Interop.Excel.Range excelRange = null;
    
            double[] colWidth = new double[] { 3.63, 8, 13.15, 5, 14.38, 5, 11.5, 8.38, 11.5, 5, 20 };
             string[] tableHeadTitle = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
        
        
            //向Excel中写入表格的表头
    
            //设置列水平居中和列的宽度
            for (int i = 1; i <= 11; i++)
            {
                excelRange = objExcel.get_Range(objExcel.Cells[1,i],objExcel.Cells[50000,i]);
                excelRange.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                excelRange.ColumnWidth = colWidth[i-1];
                excelRange.Font.Size = 11;
            }
    
            //写入标头
            for (int i = 1; i <= 3; i++)
            {
                ((Microsoft.Office.Interop.Excel.Range)objExcel.Cells[1,i]).Borders.Weight = 2;
                objExcel.Cells[1,i] = tableHeadTitle[i - 1];
            }
    
            //合并4、5格,并填入列名:d
            excelRange = objExcel.get_Range(objExcel.Cells[1,4], objExcel.Cells[1,5]);
            excelRange.Merge(Missing.Value);
            excelRange.Borders.Weight = 2;
            excelRange.set_Value(System.Reflection.Missing.Value, "d");
    
            ......
    
            System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture;
             //设置EXCEL是否可见
            objExcel.Visible = true;
            //保存文件
    
        }
        catch (Exception error)
        {
           AppMessageBox.ShowExceptionNoTranslate(error.Message);
           return;
        }
        finally
        {
            //关闭Excel应用   
            GC.Collect();
        }
    }
  • 相关阅读:
    listview右边显示 abcd快速选择
    显示密码
    欢迎界面动画
    web get Post测试
    使用MultiDexApplication
    获取当前运行的Activity信息
    MFC得到运行程序路径
    构建之法阅读笔记01
    个人作业1:随机生成四则运算
    软件工程第一步
  • 原文地址:https://www.cnblogs.com/lyan/p/2889238.html
Copyright © 2011-2022 走看看