I tried to parse an Excel file and process it using Excelize. I only have a URL link that can be used to access the file.
For my case, I tested using a file I uploaded to Dropbox. The url from dropbox is like this www.dropbox.com/s/t537135761/filename.xlsx
, but somehow when I try to use this link, the Excelize throws off this error:
open: www.dropbox.com/s/t537135761/filename.xlsx: no such file or directory
The file itself is already open for public. I can browse it on incognito mode so it means it's not because of restricted access problem. It has the extension file on the URL so I assume the URL touches the actual file that can be parsed by Excelize
I'm not sure if the problem is on Dropbox itself or is on Excelize, but that's only the cloud storage I can use to test my code.
Anyone can tell me how to use Excelize to open file using URL link? I tried searching for another function but can't find anything.
This is roughly my code (simplified) for testing.
package main
func main() {
var urlLink = "www.dropbox.com/s/t537135761/filename.xlsx"
exlz, err := excelize.OpenFile(urlLink)
if err != {
fmt.Println(err)
return
}
defer func() {
if err = exlz.Close(); err != nil {
fmt.Println(err)
}
}
return
}
CodePudding user response:
This is the solution, below the explanation.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
excelize "github.com/xuri/excelize/v2"
)
func main() {
// note here the 1 at the end instead of 0 in your original link
openURL("https://www.dropbox.com/s/8ngoie6spyga8k1/for testing.xlsx?dl=1")
}
func openURL(urlLink string) {
data, err := getData(urlLink)
if err != nil {
panic(err)
}
// Open the ZIP file with Excelize
exlz, err := excelize.OpenReader(bytes.NewReader(data))
if err != nil {
fmt.Println("Reader", err)
return
}
lst := exlz.GetSheetList()
if len(lst) == 0 {
fmt.Println("Empty document")
return
}
fmt.Println("Sheet list:")
for _, s := range lst {
fmt.Println(s)
}
defer func() {
if err = exlz.Close(); err != nil {
fmt.Println(err)
}
}()
fmt.Println("Done")
}
func getData(url string) ([]byte, error) {
r, err := http.Get(url)
if err != nil {
panic(err)
}
defer r.Body.Close()
return ioutil.ReadAll(r.Body)
}
For URL's you need to actually fetch the data first.
The second problem is that the Dropbox link that you used does not return an actual Excel, but an HTML file with an Excel embedded in it.
You need to change dl=1
at the end. This will give you the actual Excel file.