This will do what you want. Just add this line in a button click to kick it off (with your own path and filename and sheet name, of course):
ProcessFile(@"c:\temp\", "book2.xlsx", "sheet1");
And put the code below in a form or a class or where ever you want it:
using Excel = Microsoft.Office.Interop.Excel;
private void ProcessFile(string folderPath, string inputFileName, string inputSheetName)
{
string outputFileName = "";//will change for each file
object[,] data = ReadWorksheetFromExcel(folderPath + inputFileName, inputSheetName);
StringBuilder sbRow = new StringBuilder();
string comma = "";
StringBuilder sbFile = new StringBuilder();
for (int row = 1; row <= data.GetLength(0); row++)
{
if (data[row, 1] != null && data[row, 1].ToString().Trim() != "")
{
if (sbFile.ToString() != "")
{
//write previous name to a file
System.IO.File.WriteAllText(folderPath + outputFileName, sbFile.ToString());
}
//save the value of column 1 to use as the
//file name once all the data is read for this file
outputFileName = data[row, 1].ToString().Trim() + ".csv";
sbFile.Clear();
}
for (int col = 2; col <= data.GetLength(1); col++)
{
if (data[row, col] != null && data[row, col].ToString() != "")
{
string value = data[row, col].ToString();
sbRow.Append(comma + value);
comma = ",";
}
}
sbFile.AppendLine(sbRow.ToString());
sbRow.Clear();
comma = "";
}
if (sbFile.ToString() != "")
{
//write final name to a file
System.IO.File.WriteAllText(folderPath + outputFileName + ".csv", sbFile.ToString());
}
}
public object[,] ReadWorksheetFromExcel(string ExcelFilePath, string WorksheetName)
{
var excel = new Excel.Application();
excel.DisplayAlerts = false;
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Open(ExcelFilePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet worksheet = workbook.Worksheets[WorksheetName];
Excel.Range range = worksheet.UsedRange;
object[,] values = (object[,])range.Value2;
return values;
}