如何将文本框数据导出到Excel文件?

3

我有两个文本框,即 textbox1,textbox2

我想使用按钮将这些文本框中的数据导出到Excel表格中,即 test.xlsx

有人知道如何编写代码吗?


哈哈哈... "有人知道怎么写代码实现这个吗?" 哈哈 - Sandeep Kushwah
2
@SandeepKushwah 我也是 =D - Thomas Ayoub
你有搜索一下吗?看看这个:如何将一些数据写入Excel文件 - Thomas Ayoub
我尝试了这段代码 > System.IO.File.WriteAllText("test.xlsx", textBox1.Text) - user5322023
@Abdullah:如果这个答案解决了你的问题,请将其标记为已接受的解决方案;否则,请发布你自己的解决方案。 - Sandeep Kushwah
2个回答

3

首先,在您的项目中需要添加对Excel对象库的引用。

然后,您可以将该库导入到您的表单中:

using Excel = Microsoft.Office.Interop.Excel;

您可以添加类似的代码到这里:
        var excelApp = new Excel.Application();       

        excelApp.Workbooks.Open(filePath);            
        Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;      
        workSheet.Cells[1, "A"] = textBox1.Text;
        workSheet.Cells[1, "B"] = textBox1.Text;

您还可以查看这个演练,获得详细的解释。


0
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

string myPath = tbFolderpath.Text + tbFileName.Text;//User Given Path Value
FileInfo fi = new FileInfo(myPath);
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (!fi.Exists)//To Check File exist in a location,if not exist it will create new file
{
 xlWorkBook = xlApp.Workbooks.Add(misValue);
 xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 xlWorkSheet.Cells[1, "A"] = "Name";
 xlWorkSheet.Cells[1, "B"] = "Age";
 xlWorkSheet.Cells[1, "C"] = "CurrentTime";
 var columnHeadingsRange = xlWorkSheet.Range[xlWorkSheet.Cells[1, "A"], 
                           xlWorkSheet.Cells[1, "C"]];
 columnHeadingsRange.Interior.Color = Excel.XlRgbColor.rgbYellow;//To Give Header Color
 xlWorkBook.SaveAs(myPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, 
                   misValue,misValue, misValue, misValue, 
                   Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, 
                   misValue, misValue, misValue, misValue, misValue);
}
//Already File Exist it will open the File and update the data into excel`enter code here`
var workbook = xlApp.Workbooks.Open(myPath);
xlWorkSheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);
int _lastRow = xlWorkSheet.Range["A" +xlWorkSheet.Rows.Count]. 
               End[Excel.XlDirection.xlUp].Row + 1;
xlWorkSheet.Cells[_lastRow, "A"] = Textbox1.Text;
xlWorkSheet.Cells[_lastRow, "B"] = Textbox2.Text;
DateTime currentTime = DateTime.Now;//To Get the Current Time
string formattedTime = currentTime.ToString("dd/MM/yyyy-hh:mm:ss");
xlWorkSheet.Cells[_lastRow, "C"] = formattedTime;
workbook.Save();
workbook.Close();
xlApp.Quit();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接