WEB页面下载内容导出excel
阅读原文时间:2023年07月13日阅读:1

internal class DownloadHandler : IDownloadHandler
    {
        public DownloadHandler()
        {
        }

public void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
        {
            WebBrowser ie = new WebBrowser();
            ie.Navigate(downloadItem.Url);

string strrtn = System.Web.HttpUtility.UrlDecode(downloadItem.Url);

if (strrtn.Contains("data:text/csv;charset=utf-8,"))
            {
                strrtn = strrtn.Replace("data:text/csv;charset=utf-8,", "");

string[] striparr = strrtn.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                DataTable dt = new DataTable();

string[] strcolhead = striparr[0].Split(',');
                foreach (string str in strcolhead)
                {
                    dt.Columns.Add(str);
                }
                for (int i = 1; i < striparr.Length; i++)
                {
                    DataRow dr = dt.NewRow();
                    string[] array = striparr[i].Split(',');
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        dr[j] = array[j];
                    }
                    dt.Rows.Add(dr);
                }

if (dt != null && dt.Rows.Count > 0)
                {

#region   验证可操作性

//申明保存对话框
                    SaveFileDialog dlg = new SaveFileDialog();
                    //默然文件后缀
                    dlg.DefaultExt = "xls";
                    //文件后缀列表
                    dlg.Filter = "EXCEL文件(*.XLS)|*.xls";
                    //默然路径是系统当前路径
                    //dlg.InitialDirectory = Directory.GetCurrentDirectory();
                    dlg.FileName = "管网设备.xls";
                    //打开保存对话框
                    if (dlg.ShowDialog() == DialogResult.Cancel) return;
                    //返回文件路径
                    string fileNameString = dlg.FileName;
                    //验证strFileName是否为空或值无效
                    if (string.IsNullOrEmpty(fileNameString.Trim()))
                    { return; }
                    //验证strFileName是否包含文件后缀            
                    if (fileNameString.IndexOf(".") > 0)
                    {
                        string ext = fileNameString.Substring(fileNameString.LastIndexOf(".") + 1, fileNameString.Length - (fileNameString.LastIndexOf(".") + 1));

if (ext.Trim() != "xls" && ext.Trim() != "XLS" && ext.Trim() != "Xls" && ext.Trim() != "XLs" && ext.Trim() != "xLS" && ext.Trim() != "xlS")
                        {
                            MessageBox.Show("保存Excel文件名称错误", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                    string fileNameExt = fileNameString.Substring(fileNameString.LastIndexOf("\\") + 1);
                    if (fileNameExt.IndexOf(".") == 0)
                    {
                        MessageBox.Show("请输入文件名", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    //定义表格内数据的行数和列数
                    int rowscount = dt.Rows.Count;
                    int colscount = dt.Columns.Count;
                    //行数必须大于0
                    if (rowscount <= 0)
                    {
                        MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

//列数必须大于0
                    if (colscount <= 0)
                    {
                        MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

//行数不可以大于65536
                    if (rowscount > 65536)
                    {
                        MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

//列数不可以大于255
                    if (colscount > 255)
                    {
                        MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

//验证以fileNameString命名的文件是否存在,如果存在删除它
                    FileInfo file = new FileInfo(fileNameString);
                    if (file.Exists)
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch (Exception error)
                        {
                            MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    #endregion

try
                    {
                        GemBoxExcelLiteHelper.SaveToXls(fileNameString, dt);
                    }
                    catch (Exception error)
                    {
                        MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    MessageBox.Show(fileNameString + "\n\n导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
                else
                {
                    SysMessageBox.Error("无数据");
                }

}

}
        public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
        {

}
        public bool OnDownloadUpdated(CefSharp.DownloadItem downloadItem)
        {
            return false;
        }
    }

internal class ImageDownloadHandler : IDownloadHandler
    {
        //public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, NavigationType naigationvType, bool isRedirect)
        //{
        //    if (url.Contains("application/vnd.ms-excel;base64"))
        //    {
        //        string tmpContent = url;//获取传递上来的文件内容
        //        string contentHead = "data:application/vnd.ms-excel;base64,";
        //        int startIndex = tmpContent.IndexOf(contentHead);
        //        int name_StartIndex = tmpContent.IndexOf(contentHead) + contentHead.Length;
        //        int name_EndIndex = tmpContent.IndexOf('#');
        //        string fileName = "Excel表格";
        //        if (name_EndIndex != -1)
        //        {
        //            fileName = Uri.UnescapeDataString(tmpContent.Substring(name_StartIndex, name_EndIndex - name_StartIndex));
        //            tmpContent = tmpContent.Substring(name_EndIndex + 1);
        //        }
        //        else
        //        {
        //            tmpContent = tmpContent.Substring(name_StartIndex);
        //        }
        //        byte[] output = Convert.FromBase64String(tmpContent);
        //        SaveFileDialog dialog = new SaveFileDialog();
        //        dialog.FileName = fileName + ".xls";
        //        dialog.Filter = "(Excel文件)|*.xls";
        //        DialogResult result = dialog.ShowDialog();
        //        if (result == DialogResult.OK)
        //        {
        //            using (FileStream fs = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write))
        //            {
        //                fs.Write(output, 0, output.Length);
        //                fs.Flush();
        //            }
        //            return true;
        //        }
        //    }
        //    return false;
        //}
       
        public void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
        {

if (!callback.IsDisposed)
            {
                using (callback)
                {
                    callback.Continue(@"C:\Users\" +
                            System.Security.Principal.WindowsIdentity.GetCurrent().Name +
                            @"\Downloads\" +
                            downloadItem.SuggestedFileName,
                        showDialog: true);
                }
            }
        }

public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
        {

}

public bool OnDownloadUpdated(CefSharp.DownloadItem downloadItem)
        {
            return false;
        }
    }

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章