Asp.Net에 Aspose를 적용합니다.Cells에서 Excel로 보고서 내보내기 및 스타일 설정

해결 방법:
1. 사용 가능한 Aspose를 찾습니다.Cells(돈이 있으면 정품을 사라. 누가 물건을 개발해도 쉽지 않다);
2. 네.Net 스키마에서 이 Cells를 참조합니다.
3. 함수 ToExcel을 쓰고 SetcellStyle의 함수를 써서 각 열에 스타일을 설정할 수 있습니다.
4. 버튼의 클릭 이벤트에서 이 ToExcel()을 호출하면 됩니다.
주: 더 자세히 알고 싶으면 Aspose 사이트에 가세요. 거기에 온라인 문서가 많아서 볼 수 있어요.데모 프로그램 검토를 다운로드할 수도 있습니다.
 
일부 코드는 여기에 붙이고 코드는 개선해야 할 부분이 있다. 잠시 이렇게 사용하면 나중에 쉽게 찾을 수 있다. 게다가 이 컨트롤러를 진정으로 접촉한 동지들에게 벽돌을 던진다.
ExportToExcel():
/// <summary>
		///   Aspose.Cells DataTable    Excel  
		/// </summary>
		/// <returns>    </returns>
		/// <param name="response">      ,   Response  </param>
		/// <param name="dt">   </param>
		/// <param name="FileName">   </param>
		/// <param name="SheetName">sheet </param>
		/// <param name="Title">  </param>
		/// <param name="ColTitle">   ,     </param>
		/// <param name="ColName">  ,     </param>
		/// <param name="ColWidth">  ,    </param>
		/// <param name="ColStyle">   ,    ,1=    、2=    Georgia、3=    、4=  (x)、5=2   (x,xxx.xx)、6=  (yyyy-M-d    )、7=   (0.123=12.3%)</param>
		/// <param name="ColTitleRow">        , title   1  </param>
		/// <param name="err">       </param>
		public bool ExportToExcel(System.Web.HttpResponse response,DataTable dt, string FileName, string SheetName, string Title, 
			ArrayList ColTitle, ArrayList ColName, ArrayList ColWidth, ArrayList ColStyle, int ColTitleRow, ref string err)
		{

			//            
			if (ColTitle.Count != ColName.Count || ColTitle.Count != ColWidth.Count || ColTitle.Count != ColStyle.Count)
			{
				err = "        ";
				return false;
			}

			try
			{

				Workbook workbook = new Workbook(); 

				//      
				//			string path = System.Web.HttpContext.Current.Server.MapPath("~");
				//			path = path.Substring(0, path.LastIndexOf("//"));		
				//			path += @"/designer/Workbooks/NumberFormatting.xls";				
				//			workbook.Open(path);

				//  sheet
				workbook.Worksheets.Clear();
				Worksheet worksheet = workbook.Worksheets.Add(SheetName);
				worksheet = workbook.Worksheets[0];

				Cells cells = worksheet.Cells; 
				//cells.ClearContents(0,0,60,30); 

				//    
				ArrayList styles = new ArrayList();
				styles = SetCellStyle(workbook, ColStyle);

				//  Title   ,  “xxx   ”,       
				Range w;//  
				if(ColTitleRow>0)
				{
					//Put     cell 
					cells[0,0].PutValue(Title);
					//    
					cells.SetRowHeight(0, 35);
					//     
					cells.Merge(0,0,1,(byte)ColName.Count);
					//CreateRange      :cells.CreateRange(firstrow, firstcol, rownumber, colnumber)
					w=cells.CreateRange(0,0,1,(byte)ColName.Count);
					//        Style
					//w.Style = (Aspose.Cells.Style)styles[ColStyle.Count];
					w.Style = workbook.Styles["SheetTitle"];
					}
			
				//       PutValue,  “  ,  ,  ,  ,  ,  ”
				int currow = ColTitleRow; 			
				byte curcol = 0;
				foreach(string s in ColTitle)
				{
					cells[currow,curcol++].PutValue(s);
					cells.SetRowHeight(ColTitleRow, 25);
				}
				//       Style
				w=cells.CreateRange(currow,0,1,ColName.Count);						
				w.Style = (Aspose.Cells.Style)styles[ColStyle.Count+1];	
				//         
				//w.Style = workbook.Styles["ColTitle"];//ColTitle   SetCellStyle    

				currow++;
			

				//          cell
				for(int i=0; i<dt.Rows.Count; i++)
				{
					curcol = 0;
					for(int j=0; j<ColName.Count; j++)
					{
						object val = dt.Rows[i][ColName[j].ToString()].ToString().Trim();
						switch (int.Parse(ColStyle[j].ToString()))
						{
							case 4://  
								if (val.ToString().Length>0)
									val = Int32.Parse(val.ToString());
								else
									val = "";
								break;
							case 5://2   
								if (val.ToString().Length>0)
									val = Decimal.Parse(val.ToString());
								else
									val = "";
								break;
							case 6://  
								if (val.ToString().Length>0)
									val = DateTime.Parse(val.ToString());
								else
									val = "";
								break;
							case 7://   ,1=100%
								if (val.ToString().Length>0)
									val = Decimal.Parse(val.ToString());
								else
									val = "";
								break;
							default:
								break;
						}//end switch		
						cells[currow,curcol++].PutValue(val);
					}//end for j
					currow ++;
				} //end for i
				curcol = 0;
				//     Style
				for(int i=0; i<dt.Columns.Count; i++)
				{
					w = cells.CreateRange(ColTitleRow+1, i, dt.Rows.Count, 1);
					w.Style = (Aspose.Cells.Style)styles[i];				
				}
				//w=cells.CreateRange(ColTitleRow+1,col,currow,ColName.Count);
				//w.Style=excel.Styles["Data"];

				//      
				foreach(int s in ColWidth)
					cells.SetColumnWidth(curcol++, s);

				/*
				//********        *******************************************************				
				//Set number format with built-in index
				for (int i = 0; i < 37; i ++)
				{
					cells[i, 1].PutValue(1234.5);
					//int Number = cells[i, 0].IntValue;

					//Set the display number format
					cells[i, 1].Style.Number = i;
				}

				//Set number format with custom format string
				for (int i = 1; i < 4; i ++)
				{
					cells[i, 3].PutValue(1234.5);
				
					//Set the display custom number format
					cells[i, 3].Style.Custom = cells[i, 2].StringValue;
				}
				//********        *******************************************************
				*/

				//workbook.Save(FileName, FileFormatType.Default, SaveType.OpenInExcel, System.Web.HttpContext.Current.Response);
				workbook.Save(FileName, FileFormatType.Default, SaveType.OpenInExcel, response);

				return true;
			}
			catch (Exception ex)
			{
				err = ex.Message;
				return false;
			}
		}//end ExportToExcel()
		#endregion 

스타일 설정 SetStyle():
		#region SetCellStyle()    ,          ,  case    ,       
		public ArrayList SetCellStyle(Workbook workbook, ArrayList styleindex)
		{
			//       
			ArrayList CellStyle = new ArrayList(styleindex.Count + 2);
			Aspose.Cells.Style style = null;
			for (int i=0; i<styleindex.Count; i++)
			{
				int index = workbook.Styles.Add();
				
				style = workbook.Styles[index];
				style.Name = "Custom_Style" + ((int)(i + 1)).ToString();
				style.ForegroundColor = Color.White;
				style.HorizontalAlignment = TextAlignmentType.Center;
				style.VerticalAlignment = TextAlignmentType.Center;
				style.Font.Name = "  ";
				style.Font.Size = 10;
				style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
				style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
				style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
				style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
				
				switch((int)styleindex[i])
				{
					case 1://    
						style.HorizontalAlignment = TextAlignmentType.Center;
						style.VerticalAlignment = TextAlignmentType.Center;
						break;
					case 2://    Georgia
						style.Font.Name = "Georgia";
						break;
					case 3://   
						style.HorizontalAlignment = TextAlignmentType.Left;
						break;
					case 4://    1 Decimal 0  
						style.HorizontalAlignment = TextAlignmentType.Center;
						style.Number = 1;
						break;
					case 5://2    39={Currency #,##0.00;-#,##0.00}   40={#,##0.00;[Red]-#,##0.00}
						style.HorizontalAlignment = TextAlignmentType.Right;
						style.Number = 40;
						break;
					case 6://    14 Date yyyy-m-d
						style.HorizontalAlignment = TextAlignmentType.Center;
						style.Number = 14;//        ,     
						break;
					case 7://   % 10 Percentage 0.00%   
						style.HorizontalAlignment = TextAlignmentType.Center;
						style.Number = 10;
						break;
					default:
						break;
				}//end switch
				CellStyle.Add(style);
			}

			//           style.Name = "SheetTitle";
			int sindex = workbook.Styles.Add();
			style = workbook.Styles[sindex];
			style.Name = "SheetTitle";
			style.Font.Size = 14;
			style.Font.IsBold = true;
			style.Font.Name = "  _GB2312";
			style.HorizontalAlignment = TextAlignmentType.Center;
			style.VerticalAlignment = TextAlignmentType.Center;
			style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
			style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
			style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
			style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

			CellStyle.Add(style);

			//            style.Name = "ColTitle";
			sindex = workbook.Styles.Add();
			style = workbook.Styles[sindex];
			style.Name = "ColTitle";
			style.Font.Size = 12;
			style.Font.IsBold = true;
			style.Font.Name = "  ";
			style.HorizontalAlignment = TextAlignmentType.Center;
			style.VerticalAlignment = TextAlignmentType.Center;
			style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
			style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
			style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
			style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

			CellStyle.Add(style);

			//      
			return CellStyle;
			
		}//end SetCellStyle
		#endregion
원문 주소:
http://blog.csdn.net/wsq2002/article/details/4470685원작자에게 감사하다.
공식 사이트:http://www.aspose.com/docs/display/cellsnet/Importing+Data+to+Worksheets#ImportingDatatoWorksheets-array

좋은 웹페이지 즐겨찾기