반응형

                    SpreadsheetDocument doc = SpreadsheetDocument.Open(fileInfo.LocalFilePath, false);
                    WorkbookPart workbookPart = doc.WorkbookPart;
                    Sheet sheet = workbookPart.Workbook.Sheets.GetFirstChild();
                    Worksheet worksheet = (doc.WorkbookPart.GetPartById(sheet.Id.Value) as WorksheetPart).Worksheet;
                    SharedStringTablePart stringTablePart = doc.WorkbookPart.SharedStringTablePart;
                    IEnumerable rows = worksheet.GetFirstChild().Descendants();

                    SetObtainOrderExcelHD(rows, stringTablePart);
                   

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

private void SetObtainOrderExcelHD(IEnumerable rows, SharedStringTablePart stringTablePart)
{
                List<List> listRow = new List<List>();
                List listCell = null;
                foreach (Row row in rows)
                {
                    //첫번째 해더는 버리기(셀 타이틀이라서)
                    if (row.RowIndex.Value == 1)
                    {
                        continue;
                    }

                    listCell = new List();
                    for (int i = 0; i < row.Descendants().Count(); i++)
                    {
                        listCell.Add(GetCellValue(row.Descendants().ElementAt(i), stringTablePart));
                    }
                    listRow.Add(listCell);
                }
}

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public string GetCellValue(DocumentFormat.OpenXml.Spreadsheet.Cell cell, SharedStringTablePart stringTablePart)
{
            string value = string.Empty;
            if (cell.CellValue != null)
            {
                value = cell.CellValue.InnerXml;
                if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
                {
                    value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
                }

                //날짜 데이터는 아래와 같이 해줘야함.
                if (cell.StyleIndex != null && "8".Equals(cell.StyleIndex.InnerText))
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        DateTime cellDate = DateTime.FromOADate(Convert.ToDouble(cell.CellValue.InnerText));

                        if (cellDate != null)
                        {
                            value = cellDate.ToString("yyyy-MM-dd");
                        }
                    }
                    
                }

            }
            return value;
}


            

반응형

'API > C#' 카테고리의 다른 글

OpenXML Excel Write Download  (0) 2019.12.10
C# Instagram API  (1) 2018.05.04
반응형


            MemoryStream mem = new MemoryStream();
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);
            try
            {
                WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
                workbookpart.Workbook = new Workbook();
                WorksheetPart worksheetPart = workbookpart.AddNewPart();
                worksheetPart.Worksheet = new Worksheet(new SheetData());
                Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
                Sheet sheet = new Sheet()
                {
                    Id = spreadsheetDocument.WorkbookPart.
                    GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "Sheet1"
                };
                sheets.Append(sheet);

                DataSet dsResult = GetExcelData();
                DataRow drRow = null;
                Cell cell = null;
                uint iRowIdx = 0;
                string[] sheetArray = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
                for (int i = 0; i < dsResult.Tables[0].Rows.Count; i++)
                {
                    drRow = dsResult.Tables[0].Rows[i];
                    iRowIdx = Convert.ToUInt32(i + 1);

                    for (int j = 0; j < sheetArray.Length; j++)
                    {
                        cell = InsertCellInWorksheet(sheetArray[j], iRowIdx, worksheetPart);
                        cell.CellValue = new CellValue(drRow[j].ToString());
                        cell.DataType = new EnumValue(CellValues.String);
                    }
                }
                workbookpart.Workbook.Save();
                spreadsheetDocument.Close();

                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + "EAS04030.xlsx");
                Response.AddHeader("Content-Length", mem.ToArray().Length.ToString());
                Response.ContentType = "application/vnd.ms-excel";
                Response.BinaryWrite(mem.ToArray());
                Response.Flush();
                Response.Close();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                spreadsheetDocument.Dispose();

            }

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

private Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
{
            Worksheet worksheet = worksheetPart.Worksheet;
            SheetData sheetData = worksheet.GetFirstChild();
            string cellReference = columnName + rowIndex;

            // If the worksheet does not contain a row with the specified row index, insert one.
            Row row;
            if (sheetData.Elements().Where(r => r.RowIndex == rowIndex).Count() != 0)
            {
                row = sheetData.Elements().Where(r => r.RowIndex == rowIndex).First();
            }
            else
            {
                row = new Row() { RowIndex = rowIndex };
                sheetData.Append(row);
            }

            // If there is not a cell with the specified column name, insert one.  
            if (row.Elements().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
            {
                return row.Elements().Where(c => c.CellReference.Value == cellReference).First();
            }
            else
            {
                // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
                Cell refCell = null;
                foreach (Cell cell in row.Elements())
                {
                    if (cell.CellReference.Value.Length == cellReference.Length)
                    {
                        if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
                        {
                            refCell = cell;
                            break;
                        }
                    }
                }

                Cell newCell = new Cell() { CellReference = cellReference };
                row.InsertBefore(newCell, refCell);

                worksheet.Save();
                return newCell;
            }
}

반응형

'API > C#' 카테고리의 다른 글

OpenXML Excel Read Uplo  (0) 2019.12.10
C# Instagram API  (1) 2018.05.04
반응형

//client_id, redirect_uri 값 넘기고 code 받아오기

var client_id = "인스타에서 부여받은 Cient ID";

var redirect_uri = "인스타에 등록된 Valid redirect URIs 값";

Response.Redirect("https://api.instagram.com/oauth/authorize/?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=code");



** Cient ID는 어디서 구하는가??

https://instagram.com/developer

여기서 발급 받는데 발급 받는 방법은 Google 검색 하면 자세히 나와 있습니다. 그러므로 패스~! 절대로 귀찮아서 그런건 아닌걸로! 


//redirect 된 곳에서 Request["code"]로 code값 받아 온후 아래 method에 값을 넘겨 줌

private void getToken(string code)

{

try

{

NameValueCollection parameters = new NameValueCollection();

parameters.Add("client_id", "인스타에서 부여받은 Cient ID";);

parameters.Add("client_secret", "인스타에서 부여받은 Client Secret 값";);

parameters.Add("grant_type", "authorization_code");

parameters.Add("redirect_uri", "인스타에 등록된 Valid redirect URIs 값");

parameters.Add("code", code);


WebClient client = new WebClient();

var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);

var response = System.Text.Encoding.Default.GetString(result);


// deserializing nested JSON string to object  

var jsResult = (JObject)JsonConvert.DeserializeObject(response);

string accessToken = (string)jsResult["access_token"];

string id = jsResult["user"]["id"].ToString();

string username = jsResult["user"]["username"].ToString();


////This code register id and access token to get on client side  

//Page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken", "<script>var instagramaccessid=\"" + @"" + id + "" + "\"; var instagramaccesstoken=\"" + @"" +                                                                     accessToken + "" + "\"; check :"+ check + "</script>");


}

catch (Exception ex)

{

throw;


}

}



//토큰 값으로 인스타그램의 사진이나 정보들에 접근할 수 있는 url ( 서버단에서 C#으로 구현하면 보안이 더 좋을 것 같다. )

[javascript]

function GetPic() {

if (instagramaccesstoken != null) { 

$("#PhotosUL").html("");  

$.ajax({  

type: "GET",  

async: true,  

contentType: "application/json; charset=utf-8",  

//Recent user photos  

url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '/media/recent?access_token=' + instagramaccesstoken,  

//Most popular photos  

//url: "https://api.instagram.com/v1/media/popular?access_token=" + instagramaccesstoken,  

//For most recent pictures from a specific location:  

//url:  "https://api.instagram.com/v1/media/search?lat=[LAT]&lng=[LNG]&distance=[DST]?client_id=[ClientID]&access_token=[CODE]",  

//For min and max images  

//url: "https://api.instagram.com/v1/users/"+ userId+ "/media/recent/"+ "?access_token="+ token+ "&count=" + mediaCount+

 //"&max_id=" + mOldestId",  

//By Tags  

//url: "https://api.instagram.com/v1/tags/coffee/media/recent?client_id=[]&access_token=[]",  

//To get a user’s detail  

//url: "https://api.instagram.com/v1/users/usert_id/?access_token=youraccesstoken",  

dataType: "jsonp",  

cache: false,  

success: function (data) {  

if (data == "") {  

alert('NULL');

} else {

console.log("Login 성공");

console.log(data["data"]);

var str = "";

for (var i = 0; i < data["data"].length; i++) {

str += "<li style='float:left;list-style:none;'><a target='_blank' href='" + data.data[i].link + "'>

  <img src='" + data.data[i].images.thumbnail.url +"'></img></a></li>";

}

$('#PhotosUL').html(str);

App.instaWin.show();

//App.instaPanel.doLayout();

}  

}  

});

}

}


그래서 C# 예제!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

NameValueCollection parameters = new NameValueCollection();

//위의 코드에서 받은 access_token 값을 URL에 붙여 GET방식으로 넘겨 주면 됨 ( 내가 못하는건지 모르겠지만 POST방식은 실패...허허 인스타가 GET방식만 받는듯!!!)

string url = @"https://api.instagram.com/v1/users/" + Session["Id"].ToString() + "/media/recent?access_token="+ 토큰값;

WebRequest req = WebRequest.Create(url);

req.Method = "GET";

req.ContentType = "application/json; charset=utf-8";


HttpWebResponse response = (HttpWebResponse)req.GetResponse();

string myResponse = "";

using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))

{

myResponse = sr.ReadToEnd();

}


//json 형태로 받아서 어떤 데이터가 오는지 확인 후 필요한 데이터 뽑아 쓰면 끝!

var jsResult = (JObject)JsonConvert.DeserializeObject(myResponse);

instaImg.Src = jsResult["data"][0]["images"]["thumbnail"]["url"].ToString();

반응형

'API > C#' 카테고리의 다른 글

OpenXML Excel Read Uplo  (0) 2019.12.10
OpenXML Excel Write Download  (0) 2019.12.10