011——C#创建ecxel文件(附教程)

(一)参考文献:[C#]创建表格(.xlsx)的典型方法

(二)视频教程:https://v.qq.com/x/page/t30068qfex5.html

(三)下载地址:https://download.csdn.net/download/xiaoguoge11/11838954

        private void button1_Click(object sender, EventArgs e)
        {

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            string foldPath = "";
            if (dialog.ShowDialog() == DialogResult.OK)
               {
                    foldPath = dialog.SelectedPath + @"\";                             
              }
            textBox1.Text = foldPath;
            string filename = "";
            
            int hour = Convert.ToInt32(DateTime.Now.Hour.ToString()); //结果为0
            int min  = Convert.ToInt32(DateTime.Now.Minute.ToString()); //结果为0
            int time = hour * 60 + min;
            filename += DateTime.Now.ToString("yyyy-MM-dd");
            filename += "." + "xlsx";
            //创建表格的具体路径
            var file = @foldPath + filename;
            //如果存在此表格,进行删除操作
            if (File.Exists(file))
            {
                File.Delete(file);
            }
            using (var excel = new ExcelPackage(new FileInfo(file)))
            {

                //创建一个工作表
                var ws = excel.Workbook.Worksheets.Add("Sheet1");

                ws.Cells[1, 1].Value = DateTime.Now.ToShortTimeString().ToString();
                ws.Cells[1, 2].Value = time;

                //自动调整每一列的长宽高
                ws.Column(1).AutoFit();
                ws.Column(2).AutoFit();
                ws.Column(3).AutoFit();

                //保存表格信息
                excel.Save();
            }

        }

 

posted @ 2019-10-07 16:37  陆小果哥哥  阅读(500)  评论(0编辑  收藏  举报