You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程获取指定格式的当前月份所有日期

实现当前月份所有日期格式化并导出到Excel的方案

一、核心思路

  • 获取当前月份的起始与结束日期,遍历每一天
  • 按指定格式生成日期字符串(英文星期全称 + 日.月.两位年份)
  • 使用第三方库将格式化后的日期列表写入Excel文件

二、C# 实现代码示例

你提到的DateTime是.NET框架中的日期处理类,这里基于它配合EPPlus库(用于Excel操作)实现需求,需先通过NuGet安装EPPlus。

1. 生成当前月份的格式化日期列表

using System;
using System.Collections.Generic;
using System.Globalization;

class DateGenerator
{
    public static List<string> GetCurrentMonthFormattedDates()
    {
        var formattedDates = new List<string>();
        DateTime currentDate = DateTime.Today;
        // 获取当月第一天
        DateTime firstDay = new DateTime(currentDate.Year, currentDate.Month, 1);
        // 获取当月最后一天
        DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);

        // 遍历当月每一天
        for (DateTime date = firstDay; date <= lastDay; date = date.AddDays(1))
        {
            // 格式化为「星期全称 - DD.MM.YY」
            string dateStr = $"{date.ToString("dddd", CultureInfo.InvariantCulture)} - {date.ToString("dd.MM.yy")}";
            formattedDates.Add(dateStr);
        }

        return formattedDates;
    }
}

2. 将日期列表导出到Excel

using OfficeOpenXml;
using System.IO;

class ExcelExporter
{
    public static void ExportToExcel(List<string> dates, string savePath)
    {
        // 设置EPPlus非商业使用许可证
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("当月日期");
            // 写入表头(可选)
            worksheet.Cells[1, 1].Value = "日期信息";
            // 批量写入日期数据
            for (int i = 0; i < dates.Count; i++)
            {
                worksheet.Cells[i + 2, 1].Value = dates[i];
            }
            // 自动调整列宽
            worksheet.Columns[1].AutoFit();
            // 保存Excel文件
            package.SaveAs(new FileInfo(savePath));
        }
    }
}

3. 主程序调用

class Program
{
    static void Main()
    {
        var dates = DateGenerator.GetCurrentMonthFormattedDates();
        // 保存到桌面示例
        string excelPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "当月日期列表.xlsx");
        ExcelExporter.ExportToExcel(dates, excelPath);
        Console.WriteLine($"Excel文件已生成:{excelPath}");
    }
}

三、关键说明

  • 用CultureInfo.InvariantCulture确保星期输出为英文全称,不受系统区域设置影响;若需中文星期,替换为new CultureInfo("zh-CN")即可
  • 日期格式dd.MM.yy严格对应两位日、两位月、两位年份的格式要求
  • EPPlus是轻量且易用的Excel操作库,非商业场景可免费使用

内容的提问来源于stack exchange,提问作者Marco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 05:24:17