111,129
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace 从文本写入excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string str;
string line;
string myxlspath = System.IO.Directory.GetCurrentDirectory() + @"\myexcel.xls";
string mylogpath = System.IO.Directory.GetCurrentDirectory()+@"\temp.txt";
FileStream fs = new FileStream(mylogpath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);//加入System.Text.Encoding.Default出现汉字不会有乱满
sr.BaseStream.Seek(0, SeekOrigin.Begin);
Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xApp.Visible = true;
Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open(myxlspath, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
//设定预写入的页为sheet1
Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
//int lineCount = 0; //文本行数计数器出示
//while (sr.Peek() >= 0) //取文本行数
//{
// sr.ReadLine();
// lineCount ++;
// //textBox1.Text = lineCount.ToString();
// string unm = lineCount.ToString();
// textBox1.Text = unm ;
//}
while ((str = sr.ReadLine()) != null)
{
textBox1.Text += str;
//xSheet.Cells[1, 1] = str;
//xSheet.Cells[1, 2] = str;
//counter++;
}
sr.Close();
fs.Close();
}
}
}
Excel.Worksheet worksheet;
worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[1,2])就是定位第一行的一二两列。
for(int i = 0;i < 4;i++)
{
xSheet.Cells[i, i] = "csdn";
xSheet.Cells[i, i] = "论坛";
xSheet.Cells[i, i] = "中的前辈";
xSheet.Cells[i, i] = "非常感谢";
}
// 打印
xSheet.Protect(System.DateTime.Now.ToString(), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);