! 제품 버전을 정확하게 입력해 주세요.
제품 버전이 정확하게 기재되어 있지 않은 경우,
최신 버전을 기준으로 안내 드리므로
더욱 빠르고 명확한 안내를 위해
제품 버전을 정확하게 입력해 주세요!

[WPF] C# Excel 스프레드시트를 가져오고 내보내는 방법 > 온라인 스터디

본문 바로가기

Spread.NET

온라인 스터디

8. Excel 입출력 [WPF] C# Excel 스프레드시트를 가져오고 내보내는 방법

페이지 정보

작성자 GrapeCity 작성일 2022-09-15 09:37 조회 933회 댓글 0건

본문

첨부파일

특히 재무와 같은 비즈니스 환경에서 작업 시에는 주식을 모니터링하는 것이 일반적입니다. 결정을 내릴 때에는 시장이 어디에 있었는지, 현재는 어디에 있는지, 어디로 향할지에 대해서 아는 것이 핵심적입니다.


따라서 이러한 주식과 관련하여 데이터를 가져오고, 데이터를 효과적으로 평가한 다음에 명확하고 합리적인 결정을 내리는 능력이 필요합니다. 클라이언트나 최종 사용자가 모든 데이터를 쉽게 시각화하고 이해할 수 있도록 이들을 위해 데이터를 내보내는 능력은 말할 필요도 없습니다.


이 문서에서는 Spread.NET를 사용하여 VB 또는 C#에서 WPF(Windows Presentation Foundation)로 응용 프로그램을 빌드하는 방법에 대해 설명합니다.


이 응용 프로그램은 Excel 스프레드시트 가져오기 프로세스를 통해 다양한 주식 기호에 대한 3개월 분량의 종가 기록을 가져오고 검색한 다음 새 데이터를 포함한 Excel 스프레드시트를 내보내는 역할을 합니다.


다음은 VB 또는 C#에서 WPF로 Excel 스프레드시트를 가져오고 내보내는 7단계입니다.

  1. WPF 응용 프로그램 빌드

  2. WPF 응용 프로그램의 사용자 인터페이스 정의

  3. 스프레드시트 컴포넌트로 Excel 파일 가져오기

  4. Spread.NET에서 Excel 파일 내보내기

  5. 주식 데이터 기록 검색

  6. 스프레드시트에 주식 데이터 추가

  7. 데이터 소스에서 스파크라인 차트 만들기


이 응용 프로그램을 사용하면 외부 Excel 문서를 가져와 여러 주식 기호를 제공할 수 있습니다. 그러면 응용 프로그램에서 주식 기호가 처리됩니다.

  • REST API를 통해 주식의 3개월 종가 기록을 각각 검색합니다.

  • API에서 검색한 데이터 기록은 스프레드시트 컴포넌트에서 기호를 따라 표시됩니다.

  • 인라인 스파크라인 차트를 사용하여 주가 기록의 시각화를 추가합니다.

  • 처리 후 사용자는 결과 데이터를 새 Excel 문서로 내보낼 수 있습니다.


앱 빌드를 시작해보겠습니다!


WPF 응용 프로그램 빌드


먼저 Spread.NET을 다운로드하고 설치해야 합니다.


설치 시 WPF 컨트롤을 포함하십시오. 설치 프로세스가 완료된 후 Visual Studio 2022를 열고 새 WPF(.Net Framework) 데스크톱 응용 프로그램 프로젝트를 만듭니다.


제 프로젝트의 이름은 StockTrends.WPF로 지정했습니다.

프로젝트 구성


솔루션이 Visual Studio에서 로드를 완료하면 편집기에서 MainWindow.xaml을 연 다음 Visual Studio Toolbox(CTRL+ALT+X)를 엽니다.


GrapeCity Spread라는 이름의 도구 상자 섹션이 보여야 합니다.

Toolbox GC Spreadsheet


이 섹션이 보이지 않으면 스프레드시트 컴포넌트를 도구 상자에 수동으로 추가해야 합니다. 이 작업은 한 번만 하면 됩니다.


도구 상자 패널에서 마우스 오른쪽 버튼으로 컴포넌트를 추가하고 메뉴에서 항목 선택을 선택하여 목록을 스크롤한 다음 GrapeCity.WPF.SpreadSheet.UI 네임스페이스에 있는 GcSpreadSheet 컴포넌트 옆의 체크 표시를 찾아 배치하고 확인 버튼을 누릅니다.


도구 상자 항목 선택


이제 도구 상자에서 XAML 문서로 끌어서 놓을 수 있는 GcSpreadSheet 컨트롤이 생깁니다.



WPF 응용 프로그램의 사용자 인터페이스 정의


WPF 응용 프로그램의 요구 사항을 충족하도록 두 개의 행으로 구성된 단순한 창을 만들어 보겠습니다.


첫 번째 행은 Spread.NET 스프레드시트 컴포넌트가 있는 큰 영역으로 구성되어 있습니다. 아래에는 두 개의 버튼이 있습니다. 하나는 기호 스프레드시트를 가져오기 위한 버튼이고 다른 하나는 처리 후 결과를 내보내기 위한 버튼입니다.


Visual Studio 편집기에서 MainWindow.xaml을 열어 둔 상태로 기존 그리드 요소를 다음 마크업으로 바꿉니다.


MainPage.xaml 그리드 정의

<Grid>
  <Grid.RowDefinitions>
      <RowDefinition />
      <RowDefinition Height="100" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
      <ColumnDefinition />
      <ColumnDefinition />
  </Grid.ColumnDefinitions>
  <Button x:Name="btnLoadSpreadsheet" Grid.Row="1" Grid.Column="0"
      Content="Load Spreadsheet" />
  <Button x:Name="btnExportSpreadsheet" Grid.Row="1" Grid.Column="1"
      Content="Export Spreadsheet" />
</Grid>


디자이너 창은 이제 다음과 유사하게 표시됩니다.

그리드 버튼


다음으로 GcSpreadSheet 컴포넌트를 도구 상자(CTRL+ALT+X)에서 끌어다 그리드의 첫 번째 셀에 놓습니다.

Toolbox GC Spreadsheet


GcSpreadsheet 컨트롤을 처음으로 시도하면 GcSpreadsheet의 참조가 프로젝트에 추가되고 디자이너는 이 대화 상자를 다시 시작하고 표시해야 합니다.

디자이너 대화 상자 다시 시작


걱정하지 마십시오. 최신 VS2022 XAML 편집기에서는 일반적인 동작입니다. 해당 대화 상자를 닫고 GcSpreadsheet를 한 번 더 끌어다 놓아 페이지에 추가하십시오.


다음 사항과 일치하도록 스프레드시트 컴포넌트를 나타내는 XAML 요소를 편집합니다.


GcSpreadsheet용 XAML 요소

<ss:GcSpreadSheet x:Name="spreadControl" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>


디자이너는 이제 다음과 유사하게 표시됩니다.

Spreadsheet Grid Buttons



스프레드시트 컴포넌트로 Excel 파일 가져오기


구현을 위한 첫 번째 기능은 외부 Excel 파일을 Spread.NET 스프레드시트 컴포넌트로 가져오는 것입니다. 이 Excel 스프레드시트에는 응용 프로그램에서 처리할 주식 기호 목록이 포함되어 있습니다.


Microsoft.Win32 네임스페이스에서 OpenFileDialog 클래스를 사용하여 이 기능을 구현하십시오. 이 클래스가 필터를 대화 상자에 추가하므로 사용자가 기존 Excel(*.XLSX) 문서에서 빠르게 선택할 수 있습니다. 파일을 선택하면 코드의 단일 줄을 사용하여 스프레드시트가 스프레드시트 컴포넌트로 로드됩니다.


MainWindow.xaml 디자이너에서 스프레드시트 로드 버튼을 이중 클릭하여 클릭 처리기를 구현합니다. 다음과 같이 코드를 구현합니다.


btnLoadSpreadsheet_Click 함수 : C#

private void btnLoadSpreadsheet_Click(object sender, RoutedEventArgs e)
{
   Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
   ofd.DefaultExt = ".xlsx";
   ofd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
   var sel = ofd.ShowDialog();
   if (sel == true)
  {
       // one line of code to import the Excel file into Spread.NET
       spreadControl.OpenExcel(ofd.FileName);
  }
}


btnLoadSpreadsheet_Click 함수 : VB

Private Sub btnLoadSpreadsheet_Click(sender As Object, e As RoutedEventArgs) Handles btnLoadSpreadsheet.Click
  Dim ofd As Microsoft.Win32.OpenFileDialog = New Microsoft.Win32.OpenFileDialog()
  ofd.DefaultExt = ".xlsx"
  ofd.Filter = "Excel Documents (*.xlsx)|*.xlsx"
  Dim sel = ofd.ShowDialog()
  If (sel = True) Then
      ' one line of code to import the Excel file into Spread.NET
      spreadControl.OpenExcel(ofd.FileName)
  End If
End Sub


그다음에 Excel에서 주식 기호 목록을 포함하는 간단한 스프레드시트를 만듭니다. 이 문서는 하나의 열이 있는 단일 워크시트로 구성되어 있습니다.


이 열에 처리할 주식 기호를 입력합니다. 이 예제에서는 응용 프로그램 코드 자체에 중점을 둘 수 있도록 데이터 정리 또는 오류 처리를 수행하지 않습니다. 스프레드시트의 서식을 지정하는 방법에 대한 일부 규칙입니다.


행별로 유효한 하나의 주식 종목 코드만 입력합니다.

Excel 주식 목록


응용 프로그램을 실행하고 방금 만든 Excel 파일을 선택합니다.


파일은 응용 프로그램의 스프레드시트 컨트롤에 가져와 표시됩니다.

주식 파일



Spread.NET에서 Excel 파일 내보내기


이제 가져오기 프로세스가 작동하여 내보내기 기능 구현으로 넘어갈 수 있습니다. 대화 상자에서 확장 필터를 설정할 수 있으므로 Microsoft.Win32 네임스페이스에 있는 SaveFileDialog 클래스를 사용합니다. Spread.NET 컴포넌트에서 Excel 문서를 내보내는 기능은 단일 코드 줄로 달성된 간단한 프로세스이기도 합니다.


MainWindow.xaml 디자이너에서 스프레드시트 내보내기 버튼을 이중 클릭하여 클릭 이벤트 처리기 코드를 구현합니다. 다음과 같이 처리기 코드를 구현합니다.


btnExportSpreadsheet_Click 함수: C#

private void btnExportSpreadsheet_Click(object sender, RoutedEventArgs e)
{
   Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
   sfd.FileName = "SpreadNET.xlsx";
   sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
   sfd.DefaultExt = ".xlsx";
   var sel = sfd.ShowDialog();
   if (sel == true)
  {
       spreadControl.SaveExcel(sfd.FileName, GrapeCity.Windows.SpreadSheet.Data.ExcelFileFormat.XLSX);
  }
}


btn_ExportSpreadsheet_Click 함수: VB

Private Sub btnExportSpreadsheet_Click(sender As Object, e As RoutedEventArgs) Handles btnExportSpreadsheet.Click
  Dim sfd As Microsoft.Win32.SaveFileDialog = New Microsoft.Win32.SaveFileDialog()
  sfd.FileName = "SpreadNET.xlsx"
  sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx"
  sfd.DefaultExt = ".xlsx"
  Dim sel = sfd.ShowDialog()
  If (sel = True) Then
      spreadControl.SaveExcel(sfd.FileName, GrapeCity.Windows.SpreadSheet.Data.ExcelFileFormat.XLSX)
  End If
End Sub


응용 프로그램을 다시 한번 실행하고 주식 가격 스프레드시트를 다시 한번 로드한 다음 스프레드시트 내보내기 버튼을 눌러 표시된 스프레드시트의 사본을 컴퓨터에 저장합니다.



주식 데이터 기록 검색


IEX Cloud에서 무료 계정을 만들어 이 응용 프로그램의 스프레드시트에서 주식에 대한 3개월 종가 기록을 검색합니다.


계정에 등록되면 대시보드 콘솔에 로그인하여 API 토큰을 가져와 IEX Cloud API를 사용합니다("클립보드에 복사" 글리프를 클릭하여 API 토큰 복사).


IEX Cloud API 토큰


우리는 이미 API를 호출할 때 주식 기호의 전체 목록을 알고 있습니다. 따라서 단일 호출을 통해 모든 데이터를 가져오기 위해 일괄 요청 End-Point를 사용하는 것이 좋습니다.


API 통합을 구현하기 위해서는 두 개의 NuGet 패키지를 사용하겠습니다.


먼저 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 NuGet 패키지 관리 옵션을 선택합니다.


다음으로 찾아보기 탭을 선택한 다음 Newtonsoft.JSONRestSharp 패키지를 검색하고 설치하여 두 패키지를 모두 빠르고 쉽게 찾고 이 검색 문자열을 복사하여 붙여넣습니다.  


packageid:Newtonsoft.Json | packageid:RestSharp


NuGet


두 패키지를 모두 찾으면 각 패키지에 대해 설치를 클릭하여 프로젝트에 추가합니다.


다음으로 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 이름이 StockHistoryRetriever인 새 클래스를 추가합니다. 이 파일은 API 통합과 관련된 모든 코드를 캡슐화합니다. 여기에는 IEX Cloud API에서 데이터의 구조를 반영하는 두 개의 추가 클래스의 정의가 포함됩니다.


데이터 캡슐화 클래스 외에도 이 파일에는 재무 API에 대한 호출을 만들 책임이 있는 메서드가 포함됩니다. StockHistoryRetriever의 코드 목록은 다음과 같습니다(API_TOKEN 값을 IEX Cloud 대시보드의 자체 항목과 교체).


StockHistoryRetriever 함수: C#

using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;

namespace StockTrends.WPF
{
   public class StockHistoryRetriever
  {
       private const string API_TOKEN = "<YOUR PUBLISHABLE API TOKEN>";
       private const string BASE_URL = "https://cloud.iexapis.com";
       private const string API_VERSION = "beta";

       public List<ClosingStockHistory> Get3MonthHistory(List<string> symbols)
      {
           var client = new RestClient(BASE_URL);
           var endpoint = $"{API_VERSION}/stock/market/batch";
           var request = new RestRequest(endpoint, Method.Get);
           request.AddQueryParameter("symbols", string.Join(",", symbols));
           request.AddQueryParameter("types", "chart");
           request.AddQueryParameter("range", "3m");
           request.AddQueryParameter("chartCloseOnly", "true");
           request.AddQueryParameter("token", API_TOKEN);

           RestResponse resp = client.Execute(request);
           var stockHistory = JObject.Parse(resp.Content);

           var history = new List<ClosingStockHistory>();
           foreach (var symbol in symbols)
          {
               if (symbol == "")
                   continue;
               var closingStockHistory = new ClosingStockHistory();
               closingStockHistory.Symbol = symbol;
               closingStockHistory.Prices = new List<ClosingPrice>();
               var stock = stockHistory[symbol];
               var chartData = (JArray)stock["chart"];
               foreach (var itm in chartData)
              {
                   closingStockHistory.Prices.Add(new ClosingPrice()
                  {
                       Date = Convert.ToDateTime(itm["date"]),
                       Price = Convert.ToDouble(itm["close"])
                  });
              }
               history.Add(closingStockHistory);
          }

           return history;
      }
  }

   public class ClosingStockHistory
  {
       public string Symbol { get; set; }
       public List<ClosingPrice> Prices { get; set; }
  }

   public class ClosingPrice
  {
       public DateTime Date { get; set; }
       public double Price { get; set; }
  }
}


StockHistoryRetriever 함수: VB

Imports Newtonsoft.Json.Linq
Imports RestSharp
Imports System
Imports System.Collections.Generic

Public Class StockHistoryRetriever
  Private Const API_TOKEN As String = "<YOUR PUBLISHABLE API TOKEN>"
  Private Const BASE_URL As String = "https://cloud.iexapis.com"
  Private Const API_VERSION As String = "beta"

  Public Function Get3MonthHistory(ByVal symbols As List(Of String)) As List(Of ClosingStockHistory)
      Dim client = New RestClient(BASE_URL)
      Dim endpoint = $"{API_VERSION}/stock/market/batch"
      Dim request = New RestRequest(endpoint, Method.Get)
      request.AddQueryParameter("symbols", String.Join(",", symbols))
      request.AddQueryParameter("types", "chart")
      request.AddQueryParameter("range", "3m")
      request.AddQueryParameter("chartCloseOnly", "true")
      request.AddQueryParameter("token", API_TOKEN)

      Dim resp As RestResponse = client.Execute(request)
      Dim stockHistory = JObject.Parse(resp.Content)
      Dim history = New List(Of ClosingStockHistory)
      For Each symbol In symbols
          If symbol = "" Then Continue For
          Dim closingStockHistory = New ClosingStockHistory()
          closingStockHistory.Symbol = symbol
          closingStockHistory.Prices = New List(Of ClosingPrice)
          Dim stock = stockHistory(symbol)
          Dim chartData = CType(stock("chart"), JArray)
          For Each itm In chartData
              closingStockHistory.Prices.Add(New ClosingPrice() With {.ClosingDate = Convert.ToDateTime(itm("date")), .Price = Convert.ToDouble(itm("close"))})
              history.Add(closingStockHistory)
          Next
      Next
      Return history
  End Function

End Class

Public Class ClosingStockHistory
  Public Property Symbol As String
  Public Property Prices As List(Of ClosingPrice)
End Class

Public Class ClosingPrice
  Public Property ClosingDate As Date
  Public Property Price As Double
End Class



스프레드시트에 주식 데이터 추가


Spread.NET 컴포넌트에 기호 스프레드시트를 성공적으로 로드함에 따라 API에 대한 호출을 발행하고 동일한 워크시트에 다시 검색한 종가 기록을 작성하기 위해 필요한 모든 정보가 있습니다.


이 구현을 시작하려면 MainWindow.xaml.cs를 열고 다음 using 또는 Imports 문을 추가합니다.


using C#

using GrapeCity.Windows.SpreadSheet.Data;


Imports VB

Imports GrapeCity.Windows.SpreadSheet.Data


다음 메서드를 MainWindow 클래스에 추가합니다. ProcessSpreadsheet 메서드는 업로드된 문서에서 기호 목록을 읽고, API 호출을 발행하고, 현재 워크시트의 해당 행에 가격 기록 데이터를 작성하는 역할을 합니다.


ProcessSpreadsheet() 함수: C#

private void ProcessSpreadsheet()
{
   List<string> stocks = new List<string>();
   var worksheet = spreadControl.Sheets[0];
   for (var i = 0; i < worksheet.RowCount; i++)
  {
       var stockSymbol = worksheet.Cells[i, 0].Text;
       stocks.Add(stockSymbol);
  }
   StockHistoryRetriever retriever = new StockHistoryRetriever();
   var data = retriever.Get3MonthHistory(stocks);
   // calculate max columns required,
   // increase the number of columns available in the worksheet
   int maxCount = data.Max(x => x.Prices.Count());
   // 1 column for the symbol, 1 column for the sparkline
   worksheet.ColumnCount = maxCount + 1;
   //define header column style
   var headerStyleName = "HeaderStyle";
   var headerStyle = new StyleInfo()
  {
       Background = new SolidColorBrush(Colors.LightSeaGreen),
       Name = headerStyleName,
       BorderBottom = new BorderLine(Colors.SeaGreen),
       BorderRight = new BorderLine(Colors.SeaGreen)
  };
   worksheet.NamedStyles.Add(headerStyle);
   //set column header for the symbol and sparkline column - assign header style
   worksheet.ColumnHeader.Cells[0, 0].Text = "Symbol";
   worksheet.ColumnHeader.Cells[0, 0].StyleName = headerStyleName;
   bool setHeader = true;
   foreach (var stock in data)
  {
       // find stock index
       int rowIdx = 0;
       int colIdx = 0;
       spreadControl.Search(0, stock.Symbol, out rowIdx, out colIdx);
       int columnCounter = 1;
       foreach (var price in stock.Prices)
      {
           // set header to date, expand column width, set column header style
           if (setHeader)
          {
               worksheet.ColumnHeader.Cells[0, columnCounter].Text = price.Date.ToString("MM/dd/yyyy");
               worksheet.ColumnHeader.Cells[0, columnCounter].StyleName = headerStyleName;
               worksheet.Columns[columnCounter].Width = 85;
          }
           // set cell to format to currency
           worksheet.Cells[rowIdx, columnCounter].Formatter = new GeneralFormatter(FormatMode.StandardNumericMode, "c");
           worksheet.Cells[rowIdx, columnCounter].Value = price.Price;
           columnCounter++;
      }
       setHeader = false;
       spreadControl.Invalidate();
  }
}


ProcessSpreadSheet() 함수: VB

Private Sub ProcessSpreadsheet()
  Dim stocks As New List(Of String)
  Dim worksheet = spreadControl.Sheets(0)
  For i As Integer = 0 To worksheet.RowCount - 1
      Dim stockSymbol = worksheet.Cells(i, 0).Text
      stocks.Add(stockSymbol)
  Next
  Dim retriever As StockHistoryRetriever = New StockHistoryRetriever()
  Dim data = retriever.Get3MonthHistory(stocks)
  ' calculate max columns required
  ' increase the number of columns available in the worksheet
  Dim maxCount As Integer = data.Max(Function(x) x.Prices.Count)
  ' 1 column for the symbol, 1 column for the sparkline
  worksheet.ColumnCount = maxCount + 1
  ' similar to a CSS class, define header column style
  Dim headerStyleName = "HeaderStyle"
  Dim headerStyle As New StyleInfo With {.Background = New SolidColorBrush(Colors.LightSeaGreen), .Name = headerStyleName, .BorderBottom = New BorderLine(Colors.SeaGreen), .BorderRight = New BorderLine(Colors.SeaGreen)}
  worksheet.NamedStyles.Add(headerStyle)
  ' set column header for the symbol and sparkline column - assign header style
  worksheet.ColumnHeader.Cells(0, 0).Text = "Symbol"
  worksheet.ColumnHeader.Cells(0, 0).StyleName = headerStyleName
  Dim setHeader = True
  For Each stock In data
      ' find stock index
      Dim rowIdx = 0
      Dim colIdx = 0
      spreadControl.Search(0, stock.Symbol, rowIdx, colIdx)
      Dim columnCounter = 1
      For Each price In stock.Prices
          If setHeader Then
              ' set header text to date of the price,
              ' expand column width, set column header style
              worksheet.ColumnHeader.Cells(0, columnCounter).Text = price.ClosingDate.ToString("MM/dd/yyyy")
              worksheet.ColumnHeader.Cells(0, columnCounter).StyleName = headerStyleName
              worksheet.Columns(columnCounter).Width = 85
          End If
          ' set cell format to currency
          worksheet.Cells(rowIdx, columnCounter).Formatter = New GeneralFormatter(FormatMode.StandardNumericMode, "c")
          worksheet.Cells(rowIdx, columnCounter).Value = price.Price
          columnCounter += 1
      Next
      setHeader = False
      spreadControl.Invalidate()
  Next
End Sub


염두에 두어야 할 주요 사항 중 한 가지는 스프레드시트의 치수를 변경할 것이라는 점입니다.

 

먼저 업로드되면 심볼 시트는 행에 하나씩으로 정의된 주식 기호가 있는 단일 열로 구성되었습니다.


이전에 없었던 열에 작성을 시도하면 오류가 발생합니다. ColumnCount 속성을 원하는 열의 총 수로 설정하여 워크시트에서 열 수를 조정합니다.


즉시 메서드에서 OpenExcel 문을 따라 새 ProcessSpreadsheet() 함수에 호출을 추가합니다.


btnLoadSpreadsheet_Click 함수: C#

private void btnLoadSpreadsheet_Click(object sender, RoutedEventArgs e)
{
   Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
   ofd.DefaultExt = ".xlsx";
   ofd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
   var sel = ofd.ShowDialog();
   if (sel == true)
  {
       // one line of code to import the Excel file into Spread.NET
       spreadControl.OpenExcel(ofd.FileName);
       ProcessSpreadsheet();
  }
}


btnLoadSpreadsheet_Click 함수: VB

Private Sub btnLoadSpreadsheet_Click(sender As Object, e As RoutedEventArgs) Handles btnLoadSpreadsheet.Click
  Dim ofd As Microsoft.Win32.OpenFileDialog = New Microsoft.Win32.OpenFileDialog()
  ofd.DefaultExt = ".xlsx"
  ofd.Filter = "Excel Documents (*.xlsx)|*.xlsx"
  Dim sel = ofd.ShowDialog()
  If (sel = True) Then
      ' one line of code to import the Excel file into Spread.NET
      spreadControl.OpenExcel(ofd.FileName)
      ProcessSpreadsheet()
  End If
End Sub


다음으로 응용 프로그램을 다시 실행하면 이제 해당 주식 기호와 동일한 행에 표시된 3개월 종가 기록이 보이게 됩니다.


마지막으로 스프레드시트를 내보내 이 데이터를 오프라인으로 가져옵니다.

클라우드 주식 실행



데이터 소스에서 스파크라인 차트 만들기


수집한 이 모든 데이터가 인상적이더라도 데이터의 시각 표현과 쌍을 이루는 것이 더 낫습니다. 스파크라인 그래프는 이 데이터를 요약하여 해석하는 흥미로운 방법을 제공합니다.


Spread.NET를 사용하면 강력한 API를 통해 스파크라인 그래프를 만들 수 있습니다. 이러한 스파크라인은 전체적으로 사용자 정의할 수 있으며 스프레드시트에 이미 있는 데이터를 사용하여 빌드됩니다.


ProcessSpreadsheet()를 다음 코드로 변경합니다.


ProcessSpreadsheet() 함수: C#

private void ProcessSpreadsheet()
{
   List<string> stocks = new List<string>();
   var worksheet = spreadControl.Sheets[0];
   for (var i = 0; i < worksheet.RowCount; i++)
  {
       var stockSymbol = worksheet.Cells[i, 0].Text;
       stocks.Add(stockSymbol);
  }
   StockHistoryRetriever retriever = new StockHistoryRetriever();
   var data = retriever.Get3MonthHistory(stocks);
   // calculate max columns required,
   // increase the number of columns available in the worksheet
   int maxCount = data.Max(x => x.Prices.Count());
   // 1 column for the symbol, 1 column for the sparkline
   worksheet.ColumnCount = maxCount + 2;
   //set sparkline column width
   worksheet.Columns[1].Width = 500;

   //define header column style
   var headerStyleName = "HeaderStyle";
   var headerStyle = new StyleInfo()
  {
       Background = new SolidColorBrush(Colors.LightSeaGreen),
       Name = headerStyleName,
       BorderBottom = new BorderLine(Colors.SeaGreen),
       BorderRight = new BorderLine(Colors.SeaGreen)
  };
   worksheet.NamedStyles.Add(headerStyle);
   //set column header for the symbol and sparkline column - assign header style
   worksheet.ColumnHeader.Cells[0, 0].Text = "Symbol";
   worksheet.ColumnHeader.Cells[0, 0].StyleName = headerStyleName;
   worksheet.ColumnHeader.Cells[0, 1].Text = "Trend";
   worksheet.ColumnHeader.Cells[0, 1].StyleName = headerStyleName;
   bool setHeader = true;
   foreach (var stock in data)
  {
       // find stock index
       int rowIdx = 0;
       int colIdx = 0;
       spreadControl.Search(0, stock.Symbol, out rowIdx, out colIdx);
       int columnCounter = 2;
       foreach (var price in stock.Prices)
      {
           // set header to date, expand column width, set column header style
           if (setHeader)
          {
               worksheet.ColumnHeader.Cells[0, columnCounter].Text = price.Date.ToString("MM/dd/yyyy");
               worksheet.ColumnHeader.Cells[0, columnCounter].StyleName = headerStyleName;
               worksheet.Columns[columnCounter].Width = 85;
          }
           // set cell to format to currency
           worksheet.Cells[rowIdx, columnCounter].Formatter = new GeneralFormatter(FormatMode.StandardNumericMode, "c");
           worksheet.Cells[rowIdx, columnCounter].Value = price.Price;
           columnCounter++;
      }
       setHeader = false;
       // create sparkline
       var range = new CellRange(rowIdx, 2, 1, stock.Prices.Count);
       var settings = new SparklineSetting();
       settings.AxisColor = SystemColors.ActiveBorderColor;
       settings.LineWeight = 1;
       settings.ShowMarkers = true;
       settings.MarkersColor = Color.FromRgb(255, 0, 128);
       settings.ShowFirst = true;
       settings.ShowHigh = true;
       settings.ShowLast = true;
       settings.ShowNegative = true;
       settings.FirstMarkerColor = Color.FromRgb(163, 73, 164);
       settings.HighMarkerColor = Color.FromRgb(49, 78, 111);
       settings.LastMarkerColor = Color.FromRgb(0, 255, 255);
       settings.NegativeColor = Color.FromRgb(255, 255, 0);
       // set row height
       worksheet.Rows[rowIdx].Height = 250;
       worksheet.SetSparkline(rowIdx, 1, range, DataOrientation.Horizontal, SparklineType.Line, settings);
       spreadControl.Invalidate();
  }
}


ProcessSpreadSheet() VB

Private Sub ProcessSpreadsheet()
  Dim stocks As New List(Of String)
  Dim worksheet = spreadControl.Sheets(0)
  For i As Integer = 0 To worksheet.RowCount - 1
      Dim stockSymbol = worksheet.Cells(i, 0).Text
      stocks.Add(stockSymbol)
  Next
  Dim retriever As StockHistoryRetriever = New StockHistoryRetriever()
  Dim data = retriever.Get3MonthHistory(stocks)
  ' calculate max columns required
  ' increase the number of columns available in the worksheet
  Dim maxCount As Integer = data.Max(Function(x) x.Prices.Count)
  ' 1 column for the symbol, 1 column for the sparkline
  worksheet.ColumnCount = maxCount + 2
  ' set sparkline column width
  worksheet.Columns(1).Width = 500
  ' similar to a CSS class, define header column style
  Dim headerStyleName = "HeaderStyle"
  Dim headerStyle As New StyleInfo With {.Background = New SolidColorBrush(Colors.LightSeaGreen), .Name = headerStyleName, .BorderBottom = New BorderLine(Colors.SeaGreen), .BorderRight = New BorderLine(Colors.SeaGreen)}
  worksheet.NamedStyles.Add(headerStyle)
  ' set column header for the symbol and sparkline column - assign header style
  worksheet.ColumnHeader.Cells(0, 0).Text = "Symbol"
  worksheet.ColumnHeader.Cells(0, 0).StyleName = headerStyleName
  worksheet.ColumnHeader.Cells(0, 1).Text = "Trend"
  worksheet.ColumnHeader.Cells(0, 1).StyleName = headerStyleName
  Dim setHeader = True
  For Each stock In data
      ' find stock index
      Dim rowIdx = 0
      Dim colIdx = 0
      spreadControl.Search(0, stock.Symbol, rowIdx, colIdx)
      Dim columnCounter = 2
      For Each price In stock.Prices
          If setHeader Then
              ' set header text to date of the price,
              ' expand column width, set column header style
              worksheet.ColumnHeader.Cells(0, columnCounter).Text = price.ClosingDate.ToString("MM/dd/yyyy")
              worksheet.ColumnHeader.Cells(0, columnCounter).StyleName = headerStyleName
              worksheet.Columns(columnCounter).Width = 85
          End If
          ' set cell format to currency
          worksheet.Cells(rowIdx, columnCounter).Formatter = New GeneralFormatter(FormatMode.StandardNumericMode, "c")
          worksheet.Cells(rowIdx, columnCounter).Value = price.Price
          columnCounter += 1
      Next
      setHeader = False
      ' create the sparkline
      Dim range = New CellRange(rowIdx, 2, 1, stock.Prices.Count)
      Dim settings = New SparklineSetting()
      settings.AxisColor = SystemColors.ActiveBorderColor
      settings.LineWeight = 1
      settings.ShowMarkers = True
      settings.ShowFirst = True
      settings.ShowHigh = True
      settings.ShowLast = True
      settings.ShowNegative = True
      settings.FirstMarkerColor = Color.FromArgb(255, 163, 73, 164)
      settings.HighMarkerColor = Color.FromArgb(255, 49, 78, 111)
      settings.LastMarkerColor = Color.FromArgb(255, 0, 255, 255)
      settings.NegativeColor = Color.FromArgb(255, 255, 255, 0)
      ' set row height
      worksheet.Rows(rowIdx).Height = 250
      worksheet.SetSparkline(rowIdx, 1, range, DataOrientation.Horizontal, SparklineType.Line, settings)
      spreadControl.Invalidate()
  Next
End Sub


ProcessSpreadsheet() 코드는 이제 스파크라인 열에서 행 높이 및 열 너비를 설정합니다.

 

이러한 값을 설정하면 읽고 해석하기가 더 쉬워지도록 스파크라인 그래프에 더 많은 공간이 제공됩니다.


이제 코드에 색상과 같은 스파크라인 사용자 정의 설정이 포함되며 각 행에 그래프를 생성하는 데 사용되는 셀 범위를 지정할 수도 있습니다.

클라우드 스파크라인 실행


이 블로그에 대한 C# 및/또는 VB 샘플 프로젝트를 다운로드하려면 여기를 클릭하십시오.



GrapeCity 스프레드시트 컴포넌트


이 문서는 GrapeCity Spread.NET 스프레드시트 컴포넌트의 전체 기능에 대한 빙산의 일각에 불과합니다. 사용 가능한 많은 기능을 살펴보려면 문서를 검토하십시오.


스프레드시트 컴포넌트를 응용 프로그램에 통합하면 사용자의 환경을 사용자 정의하고 외부 프로그램을 참조하지 않고 익숙한 스프레드시트 기능을 제공할 수 있습니다.




지금 바로 Spread.NET을 다운로드하여 직접 테스트해보세요!

 
  • 페이스북으로 공유
  • 트위터로  공유
  • 링크 복사
  • 카카오톡으로 보내기

댓글목록

등록된 댓글이 없습니다.

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기

태그1

인기글

더보기
  • 인기 게시물이 없습니다.
메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기
이메일 : sales-kor@mescius.com | 전화 : 1670-0583 | 경기도 과천시 과천대로 7길 33, 디테크타워 B동 1107호 메시어스(주) 대표자 : 허경명 | 사업자등록번호 : 123-84-00981 | 통신판매업신고번호 : 2013-경기안양-00331 ⓒ 2024 MESCIUS inc. All rights reserved.