I don't know, for sure; but here is my guess.
"Back in the day", people used oil lamps for lighting. Oil was obtained from tallow and another source that I can't think of at the moment (being somewhat caffeine deficient), and from whales. Whale oil was the most desireable oil. It was also the most expensive. To "burn the midnight oil" meant that you had a project that was so important that you burned your expensive oil in your lamp late into the night.
There is a related saying, "Is the game worth the candle?" Again, a candle is an expendable item. Once you use it, it's gone. So if you're playing a game, it should be a good game to justify the loss of the candle. In other words, "Are the fruits of your endeavour worth the work you're putting into it?"