来る途中 ('on the way coming') sets the scene. 寄って…買って来た chains three て-form verbs showing sequence. んです adds the explanatory nuance ('the reason I have groceries is...'). 備えあれば憂いなし is a famous proverb (originally from the Chinese classic 書経): 'if there is preparation, there is no worry' = 'better safe than sorry.' The です at the end politely frames the proverb as the speaker's philosophy.