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

如何开发Google Script/插件导入指定时段Google Calendar日程至Google Docs?

Absolutely! You can absolutely build a Google Apps Script to automate importing your selected date range of Google Calendar events into a Google Docs document—this will eliminate all the manual template edits and copy-pasting you’re currently doing. Here’s a step-by-step guide to building and using the script:

How to Build the Automation Script

1. Set Up Your Google Docs Document

Open the Google Docs document you want to use for your weekly schedule (or create a new one if starting fresh).

2. Open the Apps Script Editor

Go to Extensions > Apps Script in the top menu. This will open a new tab with the script editor.

3. Replace the Default Code

Delete the default myFunction() code and paste in the following script:

function onOpen() {
  // Add a custom menu to the Docs UI for easy access
  DocumentApp.getUi()
    .createMenu('Calendar Importer')
    .addItem('Import Calendar Events', 'importCalendarEvents')
    .addToUi();
}

function importCalendarEvents() {
  const ui = DocumentApp.getUi();
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();

  // Prompt user for date range
  const startResponse = ui.prompt('Enter Start Date (YYYY-MM-DD)', 'Example: 2024-05-20', ui.ButtonSet.OK_CANCEL);
  const endResponse = ui.prompt('Enter End Date (YYYY-MM-DD)', 'Example: 2024-05-24', ui.ButtonSet.OK_CANCEL);

  if (startResponse.getSelectedButton() !== ui.Button.OK || endResponse.getSelectedButton() !== ui.Button.OK) {
    ui.alert('Operation cancelled.');
    return;
  }

  const startDate = new Date(startResponse.getResponseText());
  const endDate = new Date(endResponse.getResponseText());
  endDate.setHours(23, 59, 59); // Include all events on the end date

  // Replace with your calendar ID (find it in Google Calendar settings)
  const calendarId = 'primary'; // Use 'primary' for your main calendar, or a specific ID for shared calendars
  const calendar = CalendarApp.getCalendarById(calendarId);
  
  try {
    // Fetch events from the selected date range
    const events = calendar.getEvents(startDate, endDate);
    
    if (events.length === 0) {
      ui.alert('No events found in the selected date range.');
      return;
    }

    // Group events by date for organized display
    const eventsByDate = {};
    events.forEach(event => {
      const eventDate = Utilities.formatDate(event.getStartTime(), Session.getScriptTimeZone(), 'YYYY-MM-DD');
      if (!eventsByDate[eventDate]) {
        eventsByDate[eventDate] = [];
      }
      eventsByDate[eventDate].push(event);
    });

    // Clear existing content (optional—remove if you want to append to existing text)
    body.clear();

    // Add a title to the document
    body.appendParagraph('Weekly Schedule').setHeading(DocumentApp.ParagraphHeading.HEADING1);
    body.appendParagraph(`Date Range: ${Utilities.formatDate(startDate, Session.getScriptTimeZone(), 'MMM dd, YYYY')} to ${Utilities.formatDate(endDate, Session.getScriptTimeZone(), 'MMM dd, YYYY')}`)
      .setHeading(DocumentApp.ParagraphHeading.HEADING2);
    body.appendParagraph('');

    // Write each day's events to the document
    Object.keys(eventsByDate).sort().forEach(dateStr => {
      const date = new Date(dateStr);
      const formattedDate = Utilities.formatDate(date, Session.getScriptTimeZone(), 'EEEE, MMM dd, YYYY');
      // Add day heading
      body.appendParagraph(formattedDate).setHeading(DocumentApp.ParagraphHeading.HEADING3);
      
      // Add each event for the day
      eventsByDate[dateStr].forEach(event => {
        const startTime = Utilities.formatDate(event.getStartTime(), Session.getScriptTimeZone(), 'HH:mm');
        const endTime = Utilities.formatDate(event.getEndTime(), Session.getScriptTimeZone(), 'HH:mm');
        const eventTitle = `${startTime} - ${endTime}: ${event.getTitle()}`;
        
        // Append event title
        const eventPara = body.appendParagraph(eventTitle);
        eventPara.setBold(true);
        
        // Append event description if it exists
        const description = event.getDescription();
        if (description) {
          body.appendParagraph(`Details: ${description}`).setIndentStart(20);
        }
        
        // Append event location if it exists
        const location = event.getLocation();
        if (location) {
          body.appendParagraph(`Location: ${location}`).setIndentStart(20);
        }
        
        body.appendParagraph(''); // Add space between events
      });
    });

    ui.alert('Calendar events imported successfully!');
  } catch (error) {
    ui.alert(`Error importing events: ${error.message}`);
  }
}

4. Customize the Script (Optional)

  • Calendar ID: If you want to pull events from a shared calendar instead of your primary one, replace 'primary' with the calendar's ID (find this in Google Calendar Settings > Integrate calendar).
  • Formatting: Adjust the date formats (e.g., change 'HH:mm' to 'h:mm a' for 12-hour time) or tweak paragraph styles (bold, indentation, headings) to match your existing template.
  • Content Clearing: If you don’t want to overwrite the entire document, remove the body.clear(); line to append events to existing content.

5. Authorize and Test the Script

  1. Save the script with a name like CalendarToDocsImporter.
  2. Run the onOpen function once—this will trigger the authorization flow. Follow the prompts to grant the script access to your Google Calendar and Docs (you’ll need to click "Advanced" and "Go to [Script Name]" to proceed, since it’s a custom script).
  3. Refresh your Google Docs page—you’ll now see a Calendar Importer menu in the top bar.
  4. Click Calendar Importer > Import Calendar Events, enter your start and end dates (in YYYY-MM-DD format), and the script will populate your document with events!
Bonus: Turn It Into a Reusable Template

Once you have the script set up, you can make a copy of the Docs document to use as a weekly template—each time you need a new schedule, just open the copy, run the importer, and you’re done.

内容的提问来源于stack exchange,提问作者Daniel Van Wetering

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:14:41