The energy ministry said it had "confirmation of various cyber attacks targeting Spanish companies", adding the attackers used so-called ransomware which blocks access to files until a ransom is paid.
Some staff computers at the firms were affected, but service and network operations were not, the ministry said.
The firms' clients were also unaffected.
It added that there had been no breach of data security.
Spain's national cryptology centre, a division of the country's intelligence services, said the ransomware used in the attacks was of the WannaCry type which locks targeted files with a secret encryption algorithm.
It affected Windows operating systems and any linked networks, it said.
Telefonica reacted by switching off all computers at its Madrid headquarters, after hundreds of PCs came under attack, a source at the company told AFP.
Telefonica staff were told in megaphone announcements to urgently shut down their workstations, the source said.
Spanish energy company Iberdrola, a client of Telefonica, meanwhile shut down its computers as a precaution, a spokesman told AFP, but later found them to be unaffected by the attacks.