我有一个问题:我需要创建一个可以从 javascript 调用的网络服务(在 C# 中),该服务返回一个在(它是一个 excel)中生成的文件,并且在 javascript 中返回一个新文件,打开一个新的文件带有此文件的窗口。 从 javascript 调用的 Web 服务已经创建。问题是,首先,返回此文件,其次是 javascript 获取(无需设法将此文件记录到光盘即可)并在新窗口中打开它。
我花了几天的时间进行搜索,返回文件的唯一解决方案就像一个字节数组,javascript甚至无法将其识别为文件,远不能在另一个窗口中打开它。我已经找到,通过ActiveX,用javascript打开光盘上的文件(a .txt),但它不好,因为首先它必须接收文件并记录它,这是它不想做的事情,但是虽然想要,但不知道是否可行。
我提前感谢您所提供的帮助。 问候。
扩展一下,代码如下:javascript:
网络服务:
public string ExportarExcel(string paginaHtml)
{
//return "<% Response.ContentType = \"application/vnd.ms-excel\" %>" + paginaHtml;
// Generamos un objeto excel Aplicación:
Microsoft.Office.Interop.Excel.Application Aplic = new Microsoft.Office.Interop.Excel.Application();
Aplic.Visible = false;
Microsoft.Office.Interop.Excel.Workbook libro = Aplic.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet hoja = (Microsoft.Office.Interop.Excel.Worksheet)libro.Worksheets[1];
if (hoja == null)
{
return null;
}
hoja.Rows.Clear();
// Chequeamos lo que nos viene y lo cargamos en el excel:
int i = 0;
int m = 1; int n = 1;
paginaHtml = paginaHtml.Replace('\r', ' ').Replace('\n', ' ');
paginaHtml = paginaHtml.Replace("\\r", " ").Replace("\\n", " ");
paginaHtml = paginaHtml.Replace(" ", " ");
paginaHtml = paginaHtml.ToLower().Replace("", "").Replace("", "");
paginaHtml = paginaHtml.Replace("><", "> <");
string[] palabra = paginaHtml.Split(' ');
while (i < palabra.Length)
{
// Code to convert html table to excel file.
}
string fichero = "HtmlToExcel-" + DateTime.Now.ToFileTime() + ".xls";
string ruta = (string)Server.MapPath("~") + fichero;
hoja.SaveAs(ruta, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, false, false, false, Type.Missing, Type.Missing, Type.Missing);
// Cerramos el fichero:
libro.Close(true, Type.Missing, Type.Missing); // Cierra el libro con cbios.
hoja = null;
Aplic.Quit();
Aplic = null;
//// Transformamos a byte[]:
byte[] fExcel = ConvertirFileToByteArray(ruta);
// Borramos Fichero:
File.Delete(ruta);
return Encoding.Unicode.GetString(fExcel);
}
public static byte[] ConvertirFileToByteArray(string ruta)
{
FileStream fs = new FileStream(ruta, FileMode.Open, FileAccess.Read);
/*Create a byte array of file stream length*/
byte[] b = new byte[fs.Length];
/*Read block of bytes from stream into the byte array*/
fs.Read(b, 0, System.Convert.ToInt32(fs.Length));
/*Close the File Stream*/
fs.Close();
return b;
}
我必须将一个页面的innerHTML 转换为excel 页面,然后在新窗口中显示该页面。你能举个例子吗???
不能使用javascript将文件保存到本地磁盘,除非使用HTML 5 local storage .
为什么需要“在新窗口中打开文件”?如果您只是从网络服务以正确的内容类型trở lại该文件,浏览器将提示保存/打开它。
Tôi là một lập trình viên xuất sắc, rất giỏi!