bremen_short_url/BackEnd/api/importXlsx2.ashx

253 lines
8.7 KiB
Plaintext

<%@ WebHandler Language="C#" Class="importXlsx2" %>
using System;
using System.Web;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Services.Protocols;
using System.Security.Cryptography;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.Collections.Generic;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.XSSF;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.POIFS;
using NPOI.Util;
using System.IO;
public class importXlsx2 : IHttpHandler {
authPermission objAuth = new authPermission();
string shortUrlHeader = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/";
public void ProcessRequest (HttpContext context) {
result objRet = new result();
DataContractJsonSerializer json = new DataContractJsonSerializer(objRet.GetType());
context.Response.ContentType = "application/json;charset=utf-8";
if (objAuth.isLogin() == false) {
objRet.ret = "no";
objRet.err_code = "9999";
objRet.message = "尚未登入!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
string xlsx_serial = (context.Request["xlsx_serial"] == null) ? "" : context.Request["xlsx_serial"].ToString();
string import_col = (context.Request["import_col"] == null) ? "" : context.Request["import_col"].ToString();
string project_uid = (context.Request["project_uid"] == null) ? "" : context.Request["project_uid"].ToString();
if (xlsx_serial == "") {
objRet.ret = "no";
objRet.err_code = "0001";
objRet.message = "無xlsx_serial!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
if (import_col == "") {
objRet.ret = "no";
objRet.err_code = "0001";
objRet.message = "無import_col!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
autoBindDataTable projectSQL = new autoBindDataTable(string.Format("select * from projects where project_uid = '{0}'", project_uid));
if (projectSQL.dataRows.Count == 0) {
objRet.ret = "no";
objRet.err_code = "0002";
objRet.message = "無此Project!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
string table_name = projectSQL.dataRows[0]["project_recTableName"].ToString();
projectSQL.disConnection();
string xlsxFileName = xlsx_serial + ".xlsx";
string filePath = string.Format("BackEnd/uploads/xlsx/{0}", xlsxFileName);
string path = System.Web.HttpContext.Current.Server.MapPath("~/");
Stream xlsxStream = new FileStream(path + filePath, FileMode.Open);
XSSFWorkbook workbook = new XSSFWorkbook(xlsxStream);
workbook.MissingCellPolicy = NPOI.SS.UserModel.MissingCellPolicy.CREATE_NULL_AS_BLANK;
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
int rowIndex = 0;
int importNum = 0;
int overNum = 0;
int rowNum = 0;
foreach (XSSFRow row in sheet) {
List<ICell> cells = row.Cells;
List<string> rowData = new List<string>();
for (int colNumber = 0; colNumber < row.LastCellNum; colNumber++) {
ICell cell = row.GetCell(colNumber, MissingCellPolicy.CREATE_NULL_AS_BLANK);
rowData.Add(cell.ToString());
}
rowNum = row.LastCellNum;
string url = rowData[int.Parse(import_col)].ToString().Trim();
if (globalClass.isURL(url))
{
string findUrlString = string.Format("select * from url where project_uid = '{0}' and url_directToUrl = '{1}' ", project_uid, url);
autoBindDataTable findUrlSQL = new autoBindDataTable(findUrlString);
string url_code = "";
if (findUrlSQL.dataRows.Count > 0)
{
urlBase objUrl = new urlBase(findUrlSQL.dataRows[0]);
//objRet.urllist.Add(objUrl);
url_code = findUrlSQL.dataRows[0]["url_Code"].ToString();
overNum++;
}
else
{
DataRow newRow = findUrlSQL.newRow;
string shor_Code = globalClass.CreateCaseRandomCode(6);
Boolean isCheck = false;
url_code = shor_Code;
while (isCheck == false)
{
string checkString = string.Format("select * from url where url_code Collate SQL_Latin1_General_CP1_CS_AS = '{0}'", shor_Code);
autoBindDataTable checkSQL = new autoBindDataTable(checkString);
if (checkSQL.dataRows.Count == 0)
{
isCheck = true;
}
else
{
shor_Code = globalClass.CreateCaseRandomCode(6);
}
checkSQL.disConnection();
}
url_code = shor_Code;
urlObj objUrl = new urlObj();
objUrl.url_uid = globalClass.CreateRandomCode(32);
objUrl.project_uid = project_uid;
objUrl.url_descript = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " 透過excel上傳匯入";
objUrl.url_directToUrl = url;
objUrl.url_Code = shor_Code;
objUrl.url_playBtn = "N";
objUrl.url_fbTag = "N";
objUrl.url_gifTag = "N";
objUrl.url_gifLink = "";
objUrl.url_fbTitle = "";
objUrl.url_fbDescript = "";
objUrl.url_fbPixel = "N";
objUrl.url_fbPixelCode = "";
objUrl.url_googleAds = "N";
objUrl.url_googleAwConversionId = "";
objUrl.url_createUid = objAuth.user_uid;
objUrl.url_photoId = "";
objUrl.updateData();
urlBase objb = new urlBase(objUrl.url_uid);
objRet.urllist.Add(objb);
importNum++;
}
row.CreateCell(row.LastCellNum).SetCellValue(shortUrlHeader + url_code);
}
else {
row.CreateCell(row.LastCellNum).SetCellValue("");
}
rowIndex++;
}
sheet.AutoSizeColumn(rowNum);
MemoryStream ms = new MemoryStream();
//workbook.Write(ms);
string xlsxPath = path + string.Format("BackEnd/uploads/xlsx/output_{0}.xlsx", xlsx_serial);
using (var fs = new FileStream(xlsxPath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
fs.Close();
}
using (var fs = new FileStream(xlsxPath, FileMode.Open, FileAccess.Read)) {
long fileSize = fs.Length;
byte[] fileBuffer = new byte[fileSize];
fs.Read(fileBuffer, 0, (int)fileSize);
//context.Response.AddHeader("Content-Length", fileSize.ToString());
//context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.xlsx\"", HttpUtility.UrlEncode(xlsx_serial, Encoding.UTF8)));
// context.Response.BinaryWrite(fileBuffer);
//context.ApplicationInstance.CompleteRequest();
//context.Response.Output.Flush();
fs.Close();
}
//FileStream file = new FileStream(xlsxPath, FileMode.Create, FileAccess.Write);
//workbook.Write(file);
//ms.WriteTo(file);
//file.Flush();
//file.Close();
//ms.Flush();
objRet.outputFile = shortUrlHeader + string.Format("BackEnd/uploads/xlsx/output_{0}.xlsx", xlsx_serial);
objRet.ret = "yes";
objRet.overyNum = overNum;
objRet.totalImportNum = importNum;
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
public bool IsReusable {
get {
return false;
}
}
public class result {
public string ret = "no";
public string err_code = "0000";
public string message = "";
public string outputFile = "";
public int totalImportNum = 0;
public int overyNum = 0;
public List<urlBase> urllist = new List<urlBase>();
}
}