我使用常用方法将html表导出到excel表中如下:
var tableToExcel = function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></br></body></html>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (data, name) {
var ctx = { worksheet: name || 'Worksheet', table: data }
var url = uri + base64(format(template, ctx));
return url;
}
}()
现在我想在不使用浏览器的情况下将excel文件保存在本地驱动器中。我尝试过以下方法
$.ajax({
type: 'POST',
url: "ImageSaving.asmx/SaveFile",
data: JSON.stringify({ url: url }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
在服务器上:
public string SaveFile(string url)
{
try
{
using (WebClient client = new WebClient())
{
client.DownloadFile(url, filePath);
}
}
catch (Exception e)
{
string s = e.ToString();
}
return "";
}
但它抛出了uri formate不正确的例外。当用浏览器点击uri时,它工作正常。但我想通过没有浏览器依赖的代码保存它。
答案 0 :(得分:0)
1)WebClient通过https://i-msdn.sec.s-msft.com/dynimg/IC822539.jpg连接到服务器 2)WebClient在C盘上保存文件(它将创建或重写)
示例:
WebClient download = new WebClient();
download.DownloadFile("https://i-msdn.sec.s-msft.com/dynimg/IC822539.jpg", "C:/Users/<UserName>/img.jpg");
WebClient需要一个协议前缀:http:// https:// ftp://