C# wrap text programmatically from excel

2019-07-23 08:15发布

I have a c# console program that downloads an .xls file that gets converted to .csv file using

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + sourceFile + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes;\"";

OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;
try
{
    conn = new OleDbConnection(strConn);
    conn.Open();


    cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
    cmd.CommandType = CommandType.Text;
    wrtr = new StreamWriter(targetFile);

    da = new OleDbDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);

In one of the columns, the text needs to be word wrapped. How can I do that? Data looks like this

"The District of Columbia
ZIP 11101.
"

The column should actually be "The District of Columbia ZIP 11101."

标签: c# excel
2条回答
女痞
2楼-- · 2019-07-23 08:56

After you supply text you should set the cell's IsTextWrapped style to true

worksheet.Cells[0, 0].Style.IsTextWrapped = true;
查看更多
家丑人穷心不美
3楼-- · 2019-07-23 09:18

Remove the line breaks using something like this:

string noWraps = source.Replace(Environment.NewLine, "");
查看更多
登录 后发表回答