Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //css_reference ExcelLibrary.dll
- using System;
- using System.IO;
- using ExcelLibrary.SpreadSheet;
- /*
- * 엑셀 파일의 각 시트를 csv 포맷으로 바꾸어주는 C# 코드입니다.
- * CS-Script (http://www.csscript.net/) 사용
- * 사용된 dll 라이브러리
- * - ExcelLibrary.dll https://www.nuget.org/packages/ExcelLibrary/
- * 작성자 : CH Kim
- */
- namespace Xls2Csv
- {
- class Xls2Csv
- {
- public static void Main(string[] args)
- {
- if (args.Length != 1)
- {
- Console.WriteLine("Usage");
- Console.WriteLine("xls2csv <xls filename>");
- return;
- }
- Xls2Csv app = new Xls2Csv();
- app.convert(args[0]);
- }
- private int convert(string filename)
- {
- // gametable.xls 를 읽는다.
- try
- {
- FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096);
- Workbook workBook = Workbook.Load(fs);
- int sheetCount = workBook.Worksheets.Count;
- if (sheetCount < 1)
- return 0;
- for (int i = 0; i < sheetCount; ++i)
- {
- Worksheet sheet = workBook.Worksheets[i];
- int rowIndex = 1;
- int lastColIndex = sheet.Cells.LastColIndex;
- int lastRowIndex = sheet.Cells.LastRowIndex;
- Row row = sheet.Cells.GetRow(rowIndex++);
- int rowCount = row.LastColIndex + 1;
- string csvFilename = sheet.Name + ".csv";
- StreamWriter file = new StreamWriter(csvFilename);
- for (int n = 0; n < rowCount; ++n)
- {
- string text = row.GetCell(n).ToString();
- if (n != 0)
- file.Write(",");
- file.Write(text);
- }
- file.WriteLine();
- row = sheet.Cells.GetRow(rowIndex++);
- for (int n = 0; n < rowCount; ++n)
- {
- string text = row.GetCell(n).ToString();
- if (n != 0)
- file.Write(",");
- file.Write(text);
- }
- file.WriteLine();
- for (int j = rowIndex; j <= lastRowIndex; ++j)
- {
- row = sheet.Cells.GetRow(j);
- if (!row.GetCell(0).IsEmpty)
- {
- for (int n = 0; n < rowCount; ++n)
- {
- Cell cell = row.GetCell(n);
- string text = cell.ToString();
- if (n != 0)
- file.Write(",");
- file.Write(text);
- }
- file.WriteLine();
- }
- }
- file.Flush();
- file.Close();
- System.Console.WriteLine(csvFilename);
- } // end of sheet count
- fs.Close();
- return sheetCount;
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.ToString());
- return 0;
- }
- }
- }
- }
Advertisement