UWInfo Blog
發表新文章
[Join] | [忘記密碼] | [Login]
搜尋

搜尋意見
文章分類-#Author#
[所有文章分類]
所有文章分類
  • ASP.NET (48)
  • ASP.NET2.0 (15)
  • ASP.NET4.0 (34)
  • JavaScript (49)
  • jQuery (26)
  • FireFox (4)
  • UW系統設定 (3)
  • SQL (39)
  • SQL 2008 (25)
  • mirror (4)
  • SVN (4)
  • IE (9)
  • IIS (20)
  • IIS6 (1)
  • 閒聊 (7)
  • W3C (6)
  • 作業系統 (9)
  • C# (24)
  • CSS (12)
  • FileServer (1)
  • HTML 5 (11)
  • CKEditor (3)
  • UW.dll (13)
  • Visual Studio (16)
  • Browser (8)
  • SEO (1)
  • Google Apps (3)
  • 網站輔助系統 (4)
  • DNS (5)
  • SMTP (4)
  • 網管 (11)
  • 社群API (3)
  • SSL (4)
  • App_Inventor (1)
  • URLRewrite (2)
  • 開發工具 (6)
  • JSON (1)
  • Excel2007 (1)
  • 試題 (3)
  • LINQ (1)
  • bootstrap (0)
  • Vue (3)
  • IIS7 (3)
  • foodpanda (2)
  • 編碼 (2)
  • 資安 (3)
  • Sourcetree (1)
  • MAUI (1)
  • CMD (1)
  • my sql (1)
最新回應
  • Newtonsoft.Json.JsonConvert.DeserializeObject 失敗的情況
    test...more
  • dotnet ef dbcontext scaffold
    ...more
  • [ASP.NET] 利用 aspnet_regiis 加密 web.config
    ...more
  • IIS ARR (reverse proxy) 服務安裝
    ...more
  • [錯誤訊息] 請加入 ScriptResourceMapping 命名的 jquery (區分大小寫)
    ...more
  • 用 Javascript 跨網頁讀取 cookie (Cookie cross page, path of cookie)
    ...more
  • 線上客服 - MSN
    本人信箱被盜用以致資料外洩,是否可以請貴平台予以協助刪除該信箱之使用謝謝囉...more
  • 插入文字到游標或選取處
    aaaaa...more
  • IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
    太感謝你了~~~你救了我被windows 認證卡了好幾天QQ...more
  • PostgreSQL 的 monitor trigger
    FOR EACH ROW 可能要改為 FOR EACH STATEMENT ...more
標籤
  • 預覽
  • 超出最大長度
  • 超出
  • 起始不標示為安全的a
  • 資料庫備份
  • 資安
  • 試,
  • 試題
  • 德蒄
  • Chrome[t]
  • iis
  • Line
  • line pay介接
  • 手機版網頁
  • server
  • IP
  • mssql 備份
  • inertSQL
  • TLS1
  • web test
  • 98
  • http 錯èª
  • AD
  • separatedi
  • DB
  • 鎖定
  • 檔案
  • vs
  • Server Err
  • 出單機
  • window
  • [t]
  • async
  • 220
  • bugzilla
  • load
  • 1021211211
  • 70
  • 中文
  • face
  • C
  • 288
  • ddd
  • Chrome
  • mod
  • Su
  • div
  • [U2]
  • GDI
  • 7853
頁數 4 / 8 上一頁 下一頁
搜尋 DB 結果:
幫輸出的 Excel 加上表頭 (NPOI, UW.ExcelPOI.DTToExcelAndWriteToClient)
我想大家一定會遇到要把資料匯出成 Excel 的需求. 以現有的工具, 大家想到作法大概都是先把資料放到一個 datatable 之中, 後叫用 UW.ExcelPOI.DTToExcelAndWriteToClient 就結束了.

前兩天遇到一個需求, 輸出的 Excel 要加上表頭, 如下圖



於是乎把  UW.ExcelPOI.DTToExcelAndWriteToClient 做了一些擴充, (其實應該說是幫 DTToWorkSheet 做了擴充), 過程如下.

1. 需求: 一個可以快速填入欄位的 Sub (method or function)
A. 每一個 Cell 可以設定內容(文字), 字型大小, 跨欄數, 對齊方式. (其它的未來再來擴充, 例如顔色).
B. 每一個 Row 由 Cell 組成, 由左到右.
C. 一次可以填多個 Row

2. 實作:
A. 先定義 Cell
    Public Class Cell
        Public Content As String
        Public Colspan As Int32 = 1
        Public Alignment As NPOI.SS.UserModel.HorizontalAlignment
        Public FontHeightInPoints As Int32 = 0

        Sub New(Content As String, Optional Colspan As Int32 = 1,
                Optional Alignment As NPOI.SS.UserModel.HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment.General,
                Optional FontHeightInPoints As Int32 = 0)
            Me.Content = Content
            Me.Colspan = Colspan
            Me.Alignment = Alignment
            Me.FontHeightInPoints = FontHeightInPoints
        End Sub
    End Class


B. Row 的格式: 我想最直的覺的就是 List(of Cell) 了吧.

C. 多個 Row 的表示法: List(Of List(Of Cell))

D. 來把 Cell 填入 WorkSheet  吧, 
Public Shared Sub AddRows(WS As HSSFSheet, ltRows As List(Of List(Of Cell)), ByRef StartRow As Int32)

共有三個參數: WS  和 ltRows 應該不用解釋了. 最後一個 StartRow 用來指定插入資料的開始 Row.

E.  完整程式碼: (程式碼不看沒關係, 但要跳到 F. 重點講解哦)
Public Shared Sub AddRows(WS As HSSFSheet, ltRows As List(Of List(Of Cell)), ByRef StartRow As Int32)
        Dim WR As HSSFRow
        If ltRows IsNot Nothing Then
            For Each ltRow As List(Of Cell) In ltRows
                WR = WS.CreateRow(StartRow)
                Dim C As Int32 = 0
                For Each cell As Cell In ltRow
                    Dim ic As NPOI.SS.UserModel.ICell = WR.CreateCell(C)
                    ic.SetCellValue(cell.Content)

                    Dim cs As NPOI.SS.UserModel.ICellStyle = WS.Workbook.CreateCellStyle()
                    cs.Alignment = cell.Alignment
                    If cell.FontHeightInPoints > 0 Then
                        Dim oFont As NPOI.SS.UserModel.IFont = WS.Workbook.CreateFont()
                        oFont.FontHeightInPoints = cell.FontHeightInPoints
                        cs.SetFont(oFont)
                    End If

                    ic.CellStyle = cs

                    If cell.Colspan > 1 Then
                        WS.AddMergedRegion(New CellRangeAddress(StartRow, StartRow, C, C + cell.Colspan - 1))
                        C += cell.Colspan - 1
                    End If
                    C += 1
                Next

                StartRow += 1
            Next
        End If
    End Sub


F. 重點講解:
這個 function 在實作時有兩個卡點:
1. 如何合併欄: 
WS.AddMergedRegion(New CellRangeAddress(StartRow, StartRow, C, C + cell.Colspan - 1))

2. 如何設定字型大小和對齊方式:
                    Dim cs As NPOI.SS.UserModel.ICellStyle = WS.Workbook.CreateCellStyle()
                    cs.Alignment = cell.Alignment
                    If cell.FontHeightInPoints > 0 Then
                        Dim oFont As NPOI.SS.UserModel.IFont = WS.Workbook.CreateFont()
                        oFont.FontHeightInPoints = cell.FontHeightInPoints
                        cs.SetFont(oFont)
                    End If

                    ic.CellStyle = cs


這裡有件有有趣的事, 我一開始是這樣寫的.
ic.CellStyle.Alignment = cell.Alignment

結果是整個 WorkSheet 的對齊方式都被改了. 我猜當 WorkSheet 初建立時, CellStyle 都是用同一個. 所以改任一個 cell 的 CellStyle 會同時改到所有 cell 的.

G. 使用方式:
        Dim ltHeader As New List(Of List(Of UW.ExcelPOI.Cell))
        Dim ltLine As New List(Of UW.ExcelPOI.Cell)
        ltLine.Add(New UW.ExcelPOI.Cell(DB.SysConfig.SYSTEM_NAME & "應收明細表", 16,
                                        NPOI.SS.UserModel.HorizontalAlignment.Center, 28))
        ltHeader.Add(ltLine)

        '第二行
        ltLine = New List(Of UW.ExcelPOI.Cell)
        ltLine.Add(New UW.ExcelPOI.Cell("期間: " & Me.txtbl_date_s.Text & " ~ " & Me.txtbl_date_e.Text, 10,
                                        NPOI.SS.UserModel.HorizontalAlignment.Left, 20))
        ltLine.Add(New UW.ExcelPOI.Cell("製表日期: " & Now.ToString("yyyy-MM-dd"), 6,
                                        NPOI.SS.UserModel.HorizontalAlignment.Right, 20))
        ltHeader.Add(ltLine)

        UW.ExcelPOI.DTToExcelAndWriteToClient(newdt, ltHeader:=ltHeader)
More...
Bike, 2017/6/4 下午 07:19:27
刪除所有的 Active Session.
今天遇到客戶的 DB  使用空間滿了. 有  "Active Transaction" 

什麼事十日都不能做, 只好刪掉所有的 Session. 使用的 SQL 如下:

SQL 2012
USE [master];

DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  
FROM sys.dm_exec_sessions
WHERE database_id  = db_id('MyDB')

EXEC(@kill);


​
For MS SQL Server 2000, 2005, 2008
USE master;

DECLARE @kill varchar(8000); SET @kill = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'  
FROM master..sysprocesses  
WHERE dbid = db_id('MyDB')

EXEC(@kill); 
More...
Bike, 2017/3/23 上午 10:54:39
SVN - cleanup 卡住
有時SVN資料夾檔案,簽入簽出會出錯,然後就完全不能用了
跑 cleanup之後,會出現這樣的訊息
Command: Update Error: Previous operation has not finished; run 'cleanup' if it was interrupted Error: Please execute the 'Cleanup' command. Completed!:


其實是SVN有個工作執行沒有結束,若要 kill 掉這個工作,就要使用 sqlite 工具
(SVN 是以 sqlite 來儲存資料)
1. 要下載 sqlite3.exe 主程式放在 SVN root 目錄下
2. 開啟 cmd, 執行 ​ sqlite3.exe .svn/wc.db "select * from work_queue"
3.刪除 work queue qlite3.exe .svn/wc.db "delete from work_queue"
​4. 把 SVN root 下的 sqlite3.exe 移走
More...
darren, 2017/3/2 下午 04:38:58
Post File With C#
Post 的資料好像會變大, 要改 Web.config
<system.web>
    <httpRuntime requestValidationMode="2.0" maxRequestLength="1024000"/>
</system.web>



程式碼如下:

public string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null)
    {
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" +
                                boundary;
        request.Method = "POST";
        request.KeepAlive = true;

        Stream memStream = new System.IO.MemoryStream();

        var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                boundary + "\r\n");
        var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                    boundary + "--");


        string formdataTemplate = "\r\n--" + boundary +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        if (formFields != null)
        {
            foreach (string key in formFields.Keys)
            {
                string formitem = string.Format(formdataTemplate, key, formFields[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }
        }

        string headerTemplate =
            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
            "Content-Type: application/octet-stream\r\n\r\n";

        for (int i = 0; i < files.Length; i++)
        {
            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            var header = string.Format(headerTemplate, "uplTheFile", files[i]);
            var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            memStream.Write(headerbytes, 0, headerbytes.Length);

            using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[1024];
                var bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    Response.Write("bytesRead: " + bytesRead.ToString() + "<br>");
                    memStream.Write(buffer, 0, bytesRead);
                }
            }
        }

        memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        request.ContentLength = memStream.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        }

        try
        {
            using (var response = request.GetResponse())
            {
                Stream stream2 = response.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                return reader2.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            return (ex.ToString());
            throw;
        }
    }
More...
Bike, 2017/1/12 下午 08:21:09
一些抓取資料庫結構及述敍用的 SQL
--抓所有的 Table
Select * from INFORMATION_SCHEMA.TABLES

--抓所有的 COLUMNS
Select * from INFORMATION_SCHEMA.COLUMNS


--抓欄位的 Description
select 
    st.name [Table],
    sc.name [Column],
    sep.value [Description]
from sys.tables st
inner join sys.columns sc on st.object_id = sc.object_id
left join sys.extended_properties sep on st.object_id = sep.major_id
                                        and sc.column_id = sep.minor_id
                                        and sep.name = 'MS_Description'
where st.name = 'TableName'
and sc.name = 'ColumnName'

--修改欄位的 Description.
EXEC sp_updateextendedproperty 
@name = N'MS_Description', @value = 'Your description',
@level0type = N'Schema', @level0name = 'dbo', 
@level1type = N'Table',  @level1name = 'TableName', 
@level2type = N'Column', @level2name = 'Name';


EXEC sp_addextendedproperty 
@name = N'MS_Description', @value = 'Code description',
@level0type = N'Schema', @level0name = 'dbo', 
@level1type = N'Table',  @level1name = 'TableName', 
@level2type = N'Column', @level2name = 'ColumnName';



--新增 Table 的 extendedproperty
EXEC sp_addextendedproperty 
@name = N'Description', @value = 'Hey, here is TableName description!',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'TableName'
GO

--修改 Table 的 extendedproperty
EXEC sp_updateextendedproperty 
@name = N'Description', @value = 'Hey, here is my description! 123',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'TableName'
GO


--讀取 Extended Property
SELECT sys.objects.name AS TableName, ep.name AS PropertyName,
       ep.value AS Description
FROM sys.objects
CROSS APPLY fn_listextendedproperty(default,
                                    'SCHEMA', schema_name(schema_id),
                                    'TABLE', name, null, null) ep
WHERE sys.objects.name NOT IN ('sysdiagrams')
ORDER BY sys.objects.name

--讀取 Column 的 Description
SELECT objtype, objname, name, value  
FROM fn_listextendedproperty (NULL, 'schema', 'dbo', 'table', 'TableName', 'column', default);  
GO

--讀取特定 Table 的 Description
SELECT *  
FROM fn_listextendedproperty (NULL, 'schema', 'dbo', 'table', 'TableName', default, default);  
GO  

--讀取 所有 Table 的 Description
SELECT *  
FROM fn_listextendedproperty (NULL, 'schema', 'dbo', 'table', default, default, default);  
GO  


--新增或修改資料表說明
IF not exists(SELECT * FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table', '資料表名稱', NULL, NULL))  
           BEGIN  
            exec sp_addextendedproperty 'MS_Description', '資料表說明', 'user', 'dbo', 'table', '資料表名稱' 
           END  
ELSE 
           BEGIN  
            exec sp_updateextendedproperty 'MS_Description', '資料表說明', 'user', 'dbo', 'table', '資料表名稱' 
           END

--新增或修改欄位說明
IF not exists(SELECT * FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table', '資料表名稱', 'column', '欄位名稱')) 
           BEGIN  
            exec sp_addextendedproperty 'MS_Description', '欄位說明', 'user', 'dbo', 'table', '資料表名稱', 'column', '欄位名稱' 
           END  
ELSE 
           BEGIN  
            exec sp_updateextendedproperty 'MS_Description', '欄位說明', 'user', 'dbo', 'table', '資料表名稱', 'column', '欄位名稱' 
           END
More...
Bike, 2016/6/29 下午 04:42:25
SQL Linked Server 的錯誤訊息: 不允許遠端資料表值函數呼叫
當我們在本地的SQL以 Linked Server方式存取遠端的資料庫,有時會出現這樣的訊息
不允許遠端資料表值函數呼叫
通常是使用 stored procedure 或是 自定義的function 會出現這樣的錯誤
這時候可以有個變通方法,就是使用 OPENQUERY 方法

原寫法 (UNTDB 是 Linked Server的 Name)
mySQL = "Select count(*) as Cnt from [UNTDB].[ShopUNT]..[V_Order_Main] ....

新寫法
mySQL = "Select count(*) as Cnt from [ShopUNT]..[V_Order_Main] ....
mySQL = "Select * from Openquery([UNTDB],'" + mySQL.Replace("'", "''") + "')";

 
More...
darren, 2015/1/26 下午 02:37:25
SqlDateTime.MinValue VS DateTime.MinValue
MS SQL 最小的 DateTime 是 1753-01-01
SqlDateTime.MinValue = 1753-01-01 00:00:00
DateTime.MinValue = 0001-01-01 00:00:00

如果要將時間塞入 DB 千萬不要小於 1753-01-01
-------------------------------------------------------
UW.DB 物件會將 null datetime 轉成 DateTime.MinValue
但再塞入 DB 時應該要將 DateTime.MinValue 換成 null 或是 SqlDateTime.MinValue
才不會出錯
 
More...
darren, 2015/1/9 上午 11:55:15
T-SQL 欄位為Empty或Null時取代成其它欄位
※ 當Nickname為空或為DBNull時, 內容改成抓欄位Name
SELECT COALESCE(NULLIF(Nickname ,''), Name) as Name2  from Employee


※ 如果Nickname為ntext時
SELECT COALESCE(NULLIF(CONVERT(NVarChar(30), Nickname),''), Name) as Name2  from Employee
 
More...
candice, 2015/1/5 下午 06:22:55
ThreadStart 未處理 Exception 造成網站Crash
最近把 shopunt 網站重啟的Log加上,發現網站有兩次時無預警的重啟
但是沒有exception log, 於是去看系統的 Event log, 發現出現以下的錯誤

應用程式: w3wp.exe
Framework 版本: v4.0.30319
描述: 處理序已終止,因為有未處理的例外狀況。
例外狀況資訊: System.Exception
堆疊:
於 UW.SQL.DTFromSQL(System.String, System.String)
於 UW.SQL.DTFromSQL(System.String, System.Data.SqlClient.SqlConnection ByRef, Boolean)
於 SHOPUNT.DB.Product.RebuildNotStopProducDT()
於 System.Threading.ExecutionContext.runTryCode(System.Object)
於 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
於 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
於 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
於 System.Threading.ThreadHelper.ThreadStart()

---------------------------------------------------------------------------------------------------------------------------------------

失敗的應用程式名稱: w3wp.exe,版本: 7.5.7601.17514,時間戳記: 0x4ce7afa2
失敗的模組名稱: KERNELBASE.dll,版本: 6.1.7601.18229,時間戳記: 0x51fb1677
例外狀況碼: 0xe0434352
錯誤位移: 0x000000000000940d
失敗的處理程序識別碼: 0x57c4
失敗的應用程式開始時間: 0x01d012faf33398f8
失敗的應用程式路徑: c:\windows\system32\inetsrv\w3wp.exe
失敗的模組路徑: C:\Windows\system32\KERNELBASE.dll
報告識別碼: 90ad2f4d-7f89-11e4-8ad2-e41f13b7d81e


原因是另開 Thread 以非同步取得非停售產品的資料時 產生 sql timeout,這時網站就整個 Crash 
約兩分鐘後才重新啟動,我想雙11網站一直Crash應該跟這個有關

改善方式:
1. RebuildNotStopProducDT 要 Try Catch 不要丟 exception 直接寄 mail 就好
2. 資料庫取得 "非停售產品" 有點沒有效率,不忙時至少要跑 4 秒,資料庫一忙就會Timeout,所以應該要把確定下架且不會販售的產品設定為停售 (Is_StopSell = 'Y'),這樣至少少了2000件產品的查詢,可以秒殺


另外 .NET 4.0 有新的物件叫做 Task 可以用來處理非同步程式,也可以處理 exception 狀況,有時間的話再來改看看
 
More...
darren, 2014/12/13 下午 05:44:05
小心設定連線字串中的Connect Timeout
今天網站升到 .Net Framework 4.0 時,突然有幾個頁面一執行就會load不停,並且造成 w3wp.exe 的CPU飆高。

經查詢之後發現,問題發生在執行SQL時;會load不停的頁面所呼叫的連線字串中,都將屬性Connection Timeout=0

,因此將Connection Timeout=0拿掉就好了。

<add key="xxxxxx" value="server={server};database={DB};uid={uid};pwd={pwd};Max Pool Size={size};Connection Timeout=0"/>

http://msdn.microsoft.com/zh-cn/library/system.data.oracleclient.oracleconnection.connectiontimeout(v=vs.110).aspx

所以在設定連線字串時,應避免將Connection Timeout設成0,否則會無限期的等待連接。


p.s. 很神奇的事是,在 .Net Framework 2.0 是正常的,但升成 4.0 後才會load不停,不知道為什麼。
More...
candice, 2014/11/5 下午 06:56:48
|< 12345678 >|
頁數 4 / 8 上一頁 下一頁
~ Uwinfo ~