操作Excel文件,读取,创建

读取Excel文件

		private IList<RegionInfo> GetRegionsFromExcel(HttpPostedFile excelFile)
		{
			IList<RegionInfo> regionList = new List<RegionInfo>();
			string filePath = Server.MapPath(FileHelper.SaveAsAccessories(excelFile, _uploadFilePath));

			//从上传到服务的文件中读取
			ExcelProvider provider = new ExcelProvider(filePath, "Sheet1");
			int rowNum = 2;
			foreach (ExcelRow row in (from x in provider select x))
			{
				RegionInfo region = new RegionInfo();
				region.RowNum = rowNum;
				region.NameEn = row.GetString(0);
				region.NameCn = row.GetString(1);
				region.CountryNameEn = row.GetString(2);

				regionList.Add(region);
				rowNum++;
			}

			regionList = regionList.OrderBy(r => r.NameEn).ToList();
			return regionList;
		}


创建Excel文件
命名空间(以为是从代码中贴出来的,有些用不到)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using CodeCamp.Common.Utilities;
using Microsoft.Office.Interop.Excel;


/// <summary>
		/// 创建excel
		/// </summary>
		/// <param name="regionListNameCn"></param>
		/// <param name="regionListNoMatch"></param>
		private void CreateExcel(IList<RegionInfo> regionListNameCn, IList<RegionInfo> regionListNoMatch)
		{
			if (regionListNameCn.Count < 1 && regionListNoMatch.Count < 1)
			{
				return;
			}

			string[] myHeader = { "城市英文名", "城市中文名", "国家英文名" };
			int rowCount = 1;
			int columnCount = 3;
			Application excelApp = new Application();
			Workbook myWorkBook = excelApp.Workbooks.Add(System.Reflection.Missing.Value);
			Range myRange = null;

			//第一个工作区:非法城市中文名数据
			Worksheet myWorkSheet = myWorkBook.Worksheets[1];
			//设置主标题
			myRange = myWorkSheet.Range["A1", "C1"];
			myRange.MergeCells = true;
			myRange.HorizontalAlignment = XlVAlign.xlVAlignCenter; // 格式为居中
			myRange.Interior.ColorIndex = 15;
			myRange.Font.Bold = true;
			myWorkSheet.Cells[1, 1] = "非法城市中文名数据";

			//设置副标题
			myRange = myWorkSheet.Range["A2", "C2"];
			myRange.Value2 = myHeader;
			myRange.Columns.AutoFit(); // 自适应宽度
			myRange.HorizontalAlignment = XlVAlign.xlVAlignCenter; // 格式为居中
			myRange.Font.Bold = true;


			int i = 3;
			foreach (RegionInfo region in regionListNameCn)
			{
				//注意表格中的Cells索引是从1开始的
				myWorkSheet.Cells[i, 1] = region.NameEn;
				myWorkSheet.Cells[i, 2] = region.NameCn;
				myWorkSheet.Cells[i, 3] = region.CountryNameEn;
				i++;
			}
			rowCount = i - 1;
			//全局自适应宽度
			myWorkSheet.Range[excelApp.Cells[1, 1], excelApp.Cells[rowCount, columnCount]].Columns.AutoFit();


			//第二工作区:未导入到留学网的城市数据
			Worksheet myWorkSheet2 = myWorkBook.Worksheets[2];
			//设置主标题
			myRange = myWorkSheet2.Range["A1", "C1"];
			myRange.MergeCells = true;
			myRange.HorizontalAlignment = XlVAlign.xlVAlignCenter;
			myRange.Interior.ColorIndex = 15;
			myRange.Font.Bold = true;
			myWorkSheet2.Cells[1, 1] = "未导入到留学网的城市数据";

			//设置副标题
			myRange = myWorkSheet2.Range["A2", "C2"];
			myRange.Value2 = myHeader;
			myRange.Columns.AutoFit(); // 自适应宽度
			myRange.HorizontalAlignment = XlVAlign.xlVAlignCenter; // 格式为居中
			myRange.Font.Bold = true;

			i = 3;
			foreach (RegionInfo region in regionListNoMatch)
			{
				myWorkSheet2.Cells[i, 1] = region.NameEn;
				myWorkSheet2.Cells[i, 2] = region.NameCn;
				myWorkSheet2.Cells[i, 3] = region.CountryNameEn;
				i++;
			}
			//全局自适应宽度(报错不知原因)
			//myWorkSheet2.Range[excelApp.Cells[1, 1], excelApp.Cells[rowCount, columnCount]].Columns.AutoFit();

			//excelApp.Visible = true;

			//保存Excel文件
			string realPathFile = GetExcelFileSaveRealPath();
			myWorkBook.SaveCopyAs(realPathFile);
			myWorkBook.Close(false, null, null);
			excelApp.Quit();
			System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorkBook);
			System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
			System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorkSheet);
			System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorkSheet2);
			myWorkBook = null;
			excelApp = null;
			myWorkSheet = myWorkSheet2 = null;

			//将保存好的Excel文件 传回客户端
			FileInfo file = new FileInfo(realPathFile);
			HttpContext.Current.Response.Clear();
			HttpContext.Current.Response.Charset = "GB2312";
			HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
			//添加头信息,为"文件下载/另存为"对话框指定默认文件名
			HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
			// 添加头信息,指定文件大小,让浏览器能够显示下载进度
			HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
			// 指定返回的是一个不能被客户端读取的流,必须被下载
			HttpContext.Current.Response.ContentType = "application/ms-excel";
			// 把文件流发送到客户端
			HttpContext.Current.Response.WriteFile(file.FullName);
			HttpContext.Current.Response.Flush();
			File.Delete(file.FullName);
		}

		//获取一个服务器真实的存储excel文件地址及文件名
		private string GetExcelFileSaveRealPath()
		{
			string virtualPath = _uploadFilePath + DateTime.Now.ToString("yyyyMM") + "/";
			string realPath = HttpContext.Current.Server.MapPath(virtualPath);
			if (!Directory.Exists(realPath))
			{
				Directory.CreateDirectory(realPath);
			}

			//GetNewVirtualFilePath方法
			//根据给定的虚拟路径及文件扩展名,获取一个以当前时间为文件名的完整虚拟文件名,确保新的虚拟文件名不存在真实文件。
			string virtualFile = FileHelper.GetNewVirtualFilePath(virtualPath, ".xlsx");

			return HttpContext.Current.Server.MapPath(virtualFile);
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值