我有一些保存在字符串中的数据,现在我想打开一个现有的Excel文件,并在填充后的空单元格中依次写入这些字符串,
示例: 我有一个文件,其中A列最多写入10个,我想要代码检查10找到一个基准并写入11,然后继续[11,B] [11,C]直到完成字符串,然后保存文件。
我正在使用Interop
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
OpenFileDialog FileExcel = new OpenFileDialog();
if (FileExcel.ShowDialog() == DialogResult.OK)
{
try
{
var sr = new StreamReader(FileExcel.FileName);
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(FileExcel.FileName);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[Convert.ToInt32(comboBox1.SelectedItem)];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
//add useful things here!
}
}