Gunfire was reported immediately following the explosion, which the Taliban said targeted a guest house attached to the embassy near a heavily protected area of the capital close to many other foreign embassies, U.N. and government buildings.
A spokesman for the Spanish foreign ministry said there had been an explosion in the embassy, which is outside the fortified "green zone", but Spanish Prime Minister Mariano Rajoy said later that the attack was not directed at the embassy itself but at the guest house.
A Taliban spokesman said the attack had targeted "an invader's guest house".
One Spanish security officer was killed but all other embassy staff were safe and unhurt, he told reporters in Madrid.
Security forces with armored vehicles were deployed around the scene in biting cold weather with at least three insurgents involved in the attack, according to one police official.
Deputy Interior Minister Ayoub Salangi said two of the attackers had been killed by snipers and a third was wounded. Security forces were proceeding with caution because they were not sure exactly how many attackers might still be inside.
As the mopping up operation went on, gunfire and several loud explosions were heard around midnight, some six hours after the attack began.
At least seven people were taken to a hospital run by the aid group Emergency, 700 meters (yards) from the Spanish embassy, according to a tweet from the organization.
Spain, which contributed to the international force in Afghanistan, withdrew the last of its troops in October although a few officers remain at the headquarters of NATO's Resolute Support Mission in Kabul.
On Wednesday, Afghan President Ashraf Ghani returned from a regional peace conference in Islamabad aimed at reviving stalled peace talks with Taliban militants following several months of relative calm in the Afghan capital.
The day before, a Taliban attack in the southern city of Kandahar killed 50 civilians and security personnel, and was only suppressed after more than 24 hours of fighting.
On Thursday, the head of Afghanistan's intelligence agency resigned over a row with Ghani, in a move that underlined the divisions among leaders of the country's security apparatus.
The Taliban has been caught up with a bloody internal power struggle but it has nevertheless been able to mount well-coordinated attacks on targets across the country.
Militants have stepped up the insurgency following the withdrawal of international forces from combat operations last year, achieving a series of successes, including seizing the northern city of Kunduz in September.