Consider two cases:
- When we need to generate all the data for a file every time
- When we need to write data to a file once and then periodically update it
First case
Clean the file before recording and write new data
UPDATE t SET t.ΠΡΡΠΈΠΊΡΠ» = '', t.ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅ = '', t.Π¦Π΅Π½Π° = '', t.ΠΠ°ΡΠ° = '' FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=filepath\sales.xlsx;', 'SELECT * FROM [ΠΠΈΡΡ1$]') AS t; INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.10.0', 'Excel 12.0;HDR=YES;Database=filepath\sales.xlsx;', 'SELECT * FROM [ΠΠΈΡΡ1$]') SELECT s.code [ΠΡΡΠΈΠΊΡΠ»], s.name [ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅], s.price [Π¦Π΅Π½Π°], s.date [ΠΠ°ΡΠ°] FROM _table AS s;
This solution, although it works, but sometimes works crookedly - it happens that new data is inserted after cleared rows. Therefore, I prefer to work like this:
EXEC master..xp_cmdshell 'del filepath\sales.xlsx'; GO EXEC master..xp_cmdshell 'copy filepath\template.xlsx filepath\sales.xlsx'; GO INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.10.0', 'Excel 12.0;HDR=YES;Database=filepath\sales.xlsx;', 'SELECT * FROM [ΠΠΈΡΡ1$]') SELECT s.code [ΠΡΡΠΈΠΊΡΠ»], s.name [ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅], s.price [Π¦Π΅Π½Π°], s.date [ΠΠ°ΡΠ°] FROM _table AS s;
I keep the file template and each time before writing, I delete the old file and create a new one according to the template.
Second case
We update the data in the file, identifying lines by (in this case) article.
UPDATE t SET t.ΠΡΡΠΈΠΊΡΠ» = s.[ΠΡΡΠΈΠΊΡΠ»], t.ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅ = s.[ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅], t.Π¦Π΅Π½Π° = s.[Π¦Π΅Π½Π°], t.ΠΠ°ΡΠ° = s.[ΠΠ°ΡΠ°] FROM OPENROWSET('Microsoft.ACE.OLEDB.10.0', 'Excel 12.0;HDR=YES;Database=filepath\sales.xlsx;', 'SELECT * FROM [ΠΠΈΡΡ1$]') AS t JOIN ( SELECT code AS ΠΡΡΠΈΠΊΡΠ», name AS ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅, price AS Π¦Π΅Π½Π°, date AS ΠΠ°ΡΠ° FROM _table ) AS s ON s.ΠΡΡΠΈΠΊΡΠ» = t.ΠΡΡΠΈΠΊΡΠ»;
In both cases , the following conditions must be met:
- The file must be closed.
- The columns in the file should be named exactly as in the request and go in the same order.
PS
Microsoft.ACE.OLEDB is a 64-bit provider. In case you need 32-bit, you should use Microsoft.Jet.OLEDB .
Microsoft.Jet.OLEDB.4 & Microsoft.ACE.OLEDB.12 This is the Microsoft.Jet.OLEDB.4.0 provider is a 32-bit SQL Server for Excel 2003 files & the Microsoft.ACE.OLEDB. 12.0 provider is used with SQL Server for any Excel files or 32-bit SQL Server for Excel 2007 files.
Here you can download drivers for the provider.
Find out the version of your server SELECT @@VERSION .