2025年12月8日 星期一

[點網]使用 openxml 從 CSV 檔轉成 excel 檔

僅供參考

參考網址:

 https://learn.microsoft.com/en-us/office/open-xml/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name

https://learn.microsoft.com/en-us/office/open-xml/getting-started

https://www.nuget.org/packages/DocumentFormat.OpenXml

https://blog.darkthread.net/blog/csvhelper/

https://www.cnblogs.com/geovindu/p/19161493


程式:

```

DataTable dataTable = ReadCsv(inputPath, encoding, delimiter);


ConvertDataTableToXls(dataTable, outputPath);


public static DataTable ReadCsv(string filePath, Encoding encoding, char delimiter)

        {

            try

            {

                using (var reader = new StreamReader(filePath, encoding))

                using (var csv = new CsvReader(reader, new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)

                {

                    Delimiter = delimiter.ToString(),

                    HasHeaderRecord = true,

                    IgnoreBlankLines = true,

                    TrimOptions = CsvHelper.Configuration.TrimOptions.Trim

                }))

                {

                    using (var dr = new CsvDataReader(csv))

                    {

                        var dt = new DataTable();

                        dt.Load(dr);

                        return dt;

                    }

                }

            }

            catch (Exception ex)

            {

                throw new Exception($"Failed to read CSV file: {ex.Message}", ex);

            }

        }


public static void ConvertDataTableToXls(DataTable dataTable, string outputPath)

        {

            try

            {

                // Create a new spreadsheet document

                using (SpreadsheetDocument document = SpreadsheetDocument.Create(outputPath, SpreadsheetDocumentType.Workbook))

                {

                    // Add a WorkbookPart to the document

                    WorkbookPart workbookPart = document.AddWorkbookPart();

                    workbookPart.Workbook = new Workbook();

 

                    // Add a WorksheetPart to the WorkbookPart

                    WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();

                    worksheetPart.Worksheet = new Worksheet(new SheetData());

 

                    // Add Sheets to the Workbook

                    Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

 

                    // Append a new worksheet and associate it with the workbook

                    Sheet sheet = new Sheet()

                    {

                        Id = workbookPart.GetIdOfPart(worksheetPart),

                        SheetId = 1,

                        Name = "Sheet1"

                    };

                    sheets.Append(sheet);

 

                    // Get the SheetData object

                    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

 

                    // Add header row

                    Row headerRow = new Row();

                    foreach (DataColumn column in dataTable.Columns)

                    {

                        Cell cell = CreateCell(column.ColumnName, CellValues.String);

                        headerRow.AppendChild(cell);

                    }

                    sheetData.AppendChild(headerRow);

 

                    // Add data rows

                    foreach (DataRow row in dataTable.Rows)

                    {

                        Row dataRow = new Row();

                        foreach (var item in row.ItemArray)

                        {

                            CellValues cellType = GetCellValueType(item);

                            string cellValue = GetCellValueAsString(item, cellType);

                            Cell cell = CreateCell(cellValue, cellType);

                            dataRow.AppendChild(cell);

                        }

                        sheetData.AppendChild(dataRow);

                    }

 

                    // Save the workbook

                    workbookPart.Workbook.Save();

                }

            }

            catch (Exception ex)

            {

                throw new Exception($"Failed to create XLS file: {ex.Message}", ex);

            }

        }


        private static Cell CreateCell(string value, CellValues cellType)

        {

            Cell cell = new Cell();

            cell.DataType = new EnumValue<CellValues>(cellType);

            cell.CellValue = new CellValue(value);

            return cell;

        }

        

        private static CellValues GetCellValueType(object value)

        {

            if (value == DBNull.Value)

                return CellValues.String;

 

            Type type = value.GetType();

 

            if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte))

                return CellValues.Number;

            else if (type == typeof(float) || type == typeof(double) || type == typeof(decimal))

                return CellValues.Number;

            else if (type == typeof(DateTime))

                return CellValues.Date;

            else if (type == typeof(bool))

                return CellValues.Boolean;

            else

                return CellValues.String;

        }


         private static string GetCellValueAsString(object value, CellValues cellType)

        {

            if (value == DBNull.Value)

                return string.Empty;

 

            switch (cellType)

            {

                case CellValues.Boolean:

                    return (bool)value ? "1" : "0";

                case CellValues.Date:

                    DateTime dateValue = (DateTime)value;

                    // Excel stores dates as OLE Automation dates

                    return dateValue.ToOADate().ToString(CultureInfo.InvariantCulture);

                case CellValues.Number:

                    return Convert.ToString(value, CultureInfo.InvariantCulture);

                default:

                    return Convert.ToString(value);

            }

        }

```

2025年11月14日 星期五

[git]git 推到別站

 # 假設你已經從 A 站 clone 下來,這時 origin 指向 A 站

git remote rename origin upstream

# 新增 B 站的遠端儲存庫

git remote add origin [B 站的 Repository URL]

# 之後你就可以 push 到 B 站了

git push -u origin main

# 如果需要,也可以從 A 站拉取更新

git pull upstream main

2025年9月23日 星期二

[windows]設定 IP

 這幾年,出門去測機,每每要改別人 windows 電腦的 IP,都找不到熟悉的介面改。

一個改 IP 的介面是越藏越深,越來越難找。

乾脆,用命令列來改反而一行解決。當然,首先,要開啟的是系統管理員權限的命令列

改成固定 IP 的命令如下:

netsh interface ipv4 set address name="eth0" static 192.168.1.5 255.255.255.0

改成 DHCP 的命令如下:

netsh interface ipv4 set address name="eth0" source=dhcp

---
1. 那個 name 的值用 ipconfig 查
2. 為何不從 左下角窗戶>齒輪>網路與網際網路>乙太網路 改呢?因為改了沒生效。
3. 從 左下角窗戶>齒輪>網路與網際網路>進階網路設定 這裡有介面卡的名字,也可以改成方便記憶或下指令的名字
4. 舊的 IP 設定介面,從 左下角窗戶>齒輪>網路與網際網路>進階網路設定 點你要的介面卡,資訊會撐開,按下「編輯」按鈕。會打開舊版的設定畫面,在這裡設定 IPv4 的值,會直接生效。

2024年11月11日 星期一

[csharp]發生 Managed Debugging Assistant 'NonComVisibleBaseClass' 錯誤

 我不知道原因,但只知道解法。從解法來看,是 VS IDE 管太多卡到舊DLL了。


In Visual Studio 2019: 

Debug Menu, Windows --> Exception settings, opens the Exception settings window. 

There expand "Managed Debugging Assistants" and finally uncheck NonComVisibleBaseClass


參考:

https://stackoverflow.com/questions/1049742/noncomvisiblebaseclass-was-detected-how-do-i-fix-this

2024年8月27日 星期二

[golang]http.HandleFunc 新的 routing pattern

 在 Go1.22 的時候,讓 http.HandleFunc 新的 routing pattern 可以用變數的形式拿到 URL 路徑裡的值


要使用這個功能,要讓 go build 使用新的編譯方法,不然它總是用舊方法編譯,這是為了相容性。


最簡單就是在 go.mod 裡加上一行 go 1.22 或是 go 1.23





https://stackoverflow.com/questions/28745161/with-gos-webserver-where-does-the-root-of-the-website-map-onto-the-filesystem


https://tip.golang.org/doc/godebug


https://programmingpercy.tech/blog/exciting-go-update-v-1-22/


https://github.com/babafemi99/up-I-go/blob/main/main.go


https://gowithore.hashnode.dev/go-up-or-go-down


https://stackoverflow.com/questions/24116147/how-to-download-file-in-browser-from-go-server


https://mileslin.github.io/2020/03/Golang/%E5%BB%BA%E7%AB%8B%E4%B8%8B%E8%BC%89%E6%AA%94%E6%A1%88%E7%9A%84-Http-Response/

2024年3月18日 星期一

[secs]HSMS timeout

 T6: Active 端

    select.req <-T6-> select.rsp

T7: Passive 端

    open -> not_select <-T7-> select

T5: Active 端

    connect_fail <-T5-> connecting

T8: msg:{B <-T8-> B...}

2024年3月7日 星期四

[csharp]C# 如何得知某個 class 有實作某個介面

 ## 方法

1. objectType.GetInterfaces().Contains(interfaceType)


2. interfaceType.IsAssignableFrom(objectType)


3. objectType.IsAssignableTo(interfaceType)


4. objectType.GetInterface(nameof(interface)) != null


## 參考來源

https://www.facebook.com/groups/1706638306295947/?multi_permalinks=3338835626409532