//导出功能
protected void btnExport(object sender, EventArgs e)
{
//用来打开下载窗口
string fileName = "中心联系方式";
Response.ContentType = "application/vnd.ms-excel";
// Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.CacheControl = "no-cache";
// Response.AddHeader("Cache-Control","no-cache");
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", System.Web.HttpUtility.UrlEncode(fileName)));
Response.Clear();
//1将数据库中的数据读取到list中,
//2设置workbook的值
//3写入到memorystream中
//4以二进制的形式写入到response流中
IList list = ContactBiz.Query(new ContactInfo());
ExcelToDB excelToDB = new ExcelToDB();
try
{
MemoryStream ms = excelToDB.ExportToExcel(fileName, list);
Response.BinaryWrite(ms.ToArray()); //ms.GetBuffer();
Response.End();
}
catch (Exception ex)
{
Logger.Write("中心联系方式导出失败,原因:" + ex.Message);
throw ex;
}
}
//导入功能
protected void Button1_Click(object sender, EventArgs e)
{
bool fileOK = false;
string path = Server.MapPath("~/Temp/");
if (FileUpload1.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowedExtensiOns= { ".xls" };
for (int i = 0; i )
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
path = path + FileUpload1.FileName;
FileUpload1.SaveAs(path);
//提示文件上传成功
//LabMessage1.Text = "文件上传成功.";
//LabMessage2.Text = "原文件路径:" + FileUpload1.PostedFile.FileName + "
" +
// "文件大小:" + FileUpload1.PostedFile.ContentLength + "字节
" +
// "文件类型:" + FileUpload1.PostedFile.ContentType + "
";
ExcelToDB excelToDB = new ExcelToDB();
IList list = excelToDB.ExcelToList(path);
IList<string> textList = new List<string>();
for (int i = 0; i )
{
ContactInfo conInfo = new ContactInfo { CenterName = list[i].CenterName };
IList list1 = ContactBiz.Query(conInfo);
if (list1.Count == 0)
{
ContactBiz.Insert(list[i]);
}
else
{
textList.Add(list[i].CenterName);//add(list[i].CenterName);
}
}
string text = "";
if (textList.Count > 0)
{
for (int i = 0; i )
{
text += textList[i];
if (textList.Count > 1 && i 1)
{
text += ",";
}
}
Response.Write("");
}
else
{
Response.Write("");
}
}
catch (Exception ex)
{
Logger.Write("文件上传失败,原因:" + ex.Message);
Response.Write("");
}
}
else
{
Response.Write("");
}
// string filePath = FileUpload1.PostedFile.FileName;//从fileupload控件获取文件的全路径
}